【编译原理】实验一 词法分析器(Java实现)

import java.util.Scanner;

public class Main {
    static String name;//存放常量名
    static String value;//存放常量值
    static String type;//常量类型
    static String err;//错误信息存放
    static int corrName;//0表示常量名错误
    static int corrValue;//0表示常量值错误
    static int int_num=0;
    static int string_num=0;
    static int float_num=0;
    static int char_num=0;//统计各种类型的常量数量

    public static void main(String[]args){
        Scanner in=new Scanner(System.in);
       System.out.println("please input a string:");
       String s=in.nextLine();
       s=s.trim();//去除首尾空格
        boolean result =s.startsWith("const")&&s.endsWith(";");
        while (!result){
            //当输入的字符串不是以const开头分号结尾,则输出错误信息,并重新输入
            System.out.println("It is not a constant declaration statement!");
            System.out.println("Please input a string again!");
            s=in.nextLine();
            s=s.trim();
            result =s.startsWith("const")&&s.endsWith(";");
        }
        Output(s);
        in.close();
    }

    //判断常量名是否合法
    public static int checkName(char[]a,int i){
        name="";
        while (a[i]!='='){
            name+=a[i];
            i++;
        }
        name=name.trim();
        String regex="[a-zA-Z_][a-zA-Z0-9_]*";
        boolean result=name.matches(regex);
        if (result) {
            corrName = 1;
        } else{
                corrName=0;
            }
        return i;
    }
    //判断常量值的合法性与常量类型
    public static int checkType(char a[],int i){
        value="";
        err="";
        while (true){
            value+=a[i];
            i++;
            char b[]=value.toCharArray();
            if(b[0]!='"'&&(a[i]==','||a[i]==';')){
                break;
            }
            else if(b[0]=='"'&&a[i]=='"'&&(a[i+1]==','||a[i+1]==';')){
                value+=a[i];
                break;
            }
            else
                continue;

        }
        System.out.println("value="+value);
        value = value.trim();
        if (corrName==1){
            //判断是否为整数
            if(value.matches("[+|-]?[0-9]*")){
                String s1=value;
                //判断符号
                if(value.charAt(0)=='+'||value.charAt(0)=='-'){
                    s1=value.substring(1);
                }
                if (s1.equals("0")||s1.matches("[1-9][0-9]*")){
                    corrValue=1;
                    type="integer";
                    int_num++;
                }else{
                    err="Wrong!The integer cannot be started whit'0";
                    corrValue=0;
                }
            }
            //判断该数是否为浮点数
            else if(value.matches("[+|-]?[0-9]*[.][0-9]*")||value.matches("[+|-]?[0-9]*[.][0-9]+e[+|-]?[0-9]*")){
                corrValue=1;
                type="float";
                float_num++;
            }
            //判断是否是char型
            else if(value.startsWith("'")&&value.endsWith("'")){
                if(value.length()==3){
                    corrValue=1;
                    type="char";
                    char_num++;
                }
                else{
                    err+="Wrong!There are more than char in .";
                    corrValue=0;
                }
            }
            //判断常量是String
            else if(value.startsWith("\"")&&value.endsWith("\"")){
                corrValue=1;
                type="String";
                string_num++;

            }
            //其他错误
            else {
                corrValue=0;
                err+="Wrong!The format of the value string is not correct!";

            }
        }
        return i;
    }
    static void Output(String s){
        char str[]=s.toCharArray();
        int i=5;
        while (i<str.length-1){
            i=checkName(str,i);
            i=checkType(str,i+1)+1;
            if (corrName==1){
                //常量值正确,输出结果
                if(corrValue==1){
                    System.out.println(name+"("+type+","+value+")");
                }
                else {
                    System.out.println(name+"("+err+")");
                }
            }
            else {
                System.out.println(name+"("+"Wrong!It is not a identifier! "+")");
            }
        }
        System.out.println("int_num="+int_num+";char_num="+char_num+";string_num"+string_num+";float_num="+float_num+".");
    }



}


测试结果:
在这里插入图片描述
补充:

import java.util.Scanner;

public class Main {
    static String name;//存放常量名
    static String value;//存放常量值
    static String type;//常量类型
    static String err;//错误信息存放
    static int corrName;//0表示常量名错误
    static int corrValue;//0表示常量值错误
    static int int_num=0;
    static int string_num=0;
    static int float_num=0;
    static int char_num=0;//统计各种类型的常量数量

    public static void main(String[]args){
        Scanner in=new Scanner(System.in);
       System.out.println("please input a string:");
       String s=in.nextLine();
       s=s.trim();//去除首尾空格
        boolean result =s.startsWith("const")&&s.endsWith(";");
        while (!result){
            //当输入的字符串不是以const开头分号结尾,则输出错误信息,并重新输入
            System.out.println("It is not a constant declaration statement!");
            System.out.println("Please input a string again!");
            s=in.nextLine();
            s=s.trim();
            result =s.startsWith("const")&&s.endsWith(";");
        }
        Output(s);
        in.close();
    }

    //判断常量名是否合法
    public static int checkName(char[]a,int i){
        name="";
        while (a[i]!='='){
            name+=a[i];
            i++;
        }
        name=name.trim();
        String regex="[a-zA-Z_][a-zA-Z0-9_]*";
        boolean result=name.matches(regex);
        if (result) {
            corrName = 1;
        } else{
                corrName=0;
            }
        return i;
    }
    //判断常量值的合法性与常量类型
    public static int checkType(char a[],int i){
        value="";
        err="";
        while (true){
            value+=a[i];
            i++;
            char b[]=value.toCharArray();
            if(b[0]!='"'&&b[0]!='\''&&(a[i]==','||a[i]==';')){
                break;
            }
            else if(b[0]=='"'&&a[i]=='"'&&(a[i+1]==','||a[i+1]==';')){
                value+=a[i];i++;
                break;
            }
            else if(b[0]=='\''&&a[i]=='\''&&(a[i+1]==','||a[i+1]==';')){
                value+=a[i];i++;
                break;
            }
            else
                continue;

        }
        System.out.println("value="+value);
        value = value.trim();
        if (corrName==1){
            //判断是否为整数
            if(value.matches("[+|-]?[0-9]*")){
                String s1=value;
                //判断符号
                if(value.charAt(0)=='+'||value.charAt(0)=='-'){
                    s1=value.substring(1);
                }
                if (s1.equals("0")||s1.matches("[1-9][0-9]*")){
                    corrValue=1;
                    type="integer";
                    int_num++;
                }else{
                    err="Wrong!The integer cannot be started whit'0";
                    corrValue=0;
                }
            }
            //判断该数是否为浮点数
            else if(value.matches("[+|-]?[0-9]*[.][0-9]*")||value.matches("[+|-]?[0-9]*[.][0-9]+e[+|-]?[0-9]*")){
                corrValue=1;
                type="float";
                float_num++;
            }
            //判断是否是char型
            else if(value.startsWith("'")&&value.endsWith("'")){
                if(value.length()==3){
                    corrValue=1;
                    type="char";
                    char_num++;
                }
                else{
                    err+="Wrong!There are more than char in .";
                    corrValue=0;
                }
            }
            //判断常量是String
            else if(value.startsWith("\"")&&value.endsWith("\"")){
                corrValue=1;
                type="String";
                string_num++;

            }
            //其他错误
            else {
                corrValue=0;
                err+="Wrong!The format of the value string is not correct!";

            }
        }
        return i;
    }
    static void Output(String s){
        char str[]=s.toCharArray();
        int i=5;
        while (i<str.length-1){
            i=checkName(str,i);
            i=checkType(str,i+1)+1;
            if (corrName==1){
                //常量值正确,输出结果
                if(corrValue==1){
                    System.out.println(name+"("+type+","+value+")");
                }
                else {
                    System.out.println(name+"("+err+")");
                }
            }
            else {
                System.out.println(name+"("+"Wrong!It is not a identifier! "+")");
            }
        }
        System.out.println("int_num="+int_num+";char_num="+char_num+";string_num"+string_num+";float_num="+float_num+".");
    }



}


在这里插入图片描述

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供一些关于编译原理词法分析器Java语言实现的信息。 首先,词法分析器编译器的第一个阶段,其任务是将输入的字符流转换为有意义的词法单元(token)序列。在Java中,可以使用诸如ANTLR、JavaCC等工具来自动生成词法分析器,也可以手动编写自己的词法分析器。 手动编写词法分析器的方法是,先定义词法单元的类型,然后使用正则表达式来描述每个词法单元的模式。接着,使用Java的Scanner类读取输入的字符流,并对其进行匹配。匹配成功后,将识别出的词法单元存储到一个token序列中,最后返回token序列。 下面是一个简单的Java词法分析器的示例代码: ``` import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Scanner; public class Lexer { private String input; private ArrayList<Token> tokens; public Lexer(String input) { this.input = input; this.tokens = new ArrayList<Token>(); } public ArrayList<Token> tokenize() { Scanner scanner = new Scanner(this.input); String pattern = "\\s*([0-9]+|[a-zA-Z]+|\\+|\\-|\\*|\\/|=)"; Pattern regex = Pattern.compile(pattern); while (scanner.hasNextLine()) { String line = scanner.nextLine(); Matcher matcher = regex.matcher(line); while (matcher.find()) { String lexeme = matcher.group(1); TokenType type = getTokenType(lexeme); Token token = new Token(type, lexeme); this.tokens.add(token); } } return this.tokens; } private TokenType getTokenType(String lexeme) { if (lexeme.matches("[0-9]+")) { return TokenType.NUMBER; } else if (lexeme.matches("[a-zA-Z]+")) { return TokenType.IDENTIFIER; } else if (lexeme.matches("\\+|\\-|\\*|\\/")) { return TokenType.OPERATOR; } else if (lexeme.equals("=")) { return TokenType.ASSIGNMENT; } else { return TokenType.UNKNOWN; } } } ``` 在这个例子中,我们使用正则表达式来描述了数字、标识符、运算符和赋值符号的模式。我们使用Scanner类来读取输入的字符流,并使用Matcher类来进行匹配。每次匹配成功后,我们将识别出的词法单元存储到一个ArrayList中,并最终返回这个ArrayList作为结果。 这只是一个简单的示例代码,实际上词法分析器实现还需要考虑很多其他的因素,比如错误处理、注释处理等。但是,希望这个例子能够给您提供一些参考。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值