无法读取字符串以在JAVA中结束

时间:2016-03-14 17:52:50

标签: java tokenize lexical-analysis

我正在尝试制作一个描述JAVA中词法分析的程序。我能够定义令牌并设置所有内容,但我在读取while循环中输入的整个字符串时遇到问题。我希望字符串能够通过do中的每一步,但我无法实现它们。如果我试着这样做而没有做,显然它没有给出准确的结果。如何读取字符串直到最后?

do {
            if (string.contains("+")) {
                lex_air[0]++;
            } else if (string.contains("-")) {
                lex_air[1]++;
            } else if (string.contains("*")) {
                lex_air[2]++;
            } else if (string.contains("/")) {
                lex_air[3]++;
            }
            if (string.contains(">")) {
                lex_log[0]++;
            } else if (string.contains("<")) {
                lex_log[1]++;
            } else if (string.contains("=")) {
                lex_log[2]++;
            } else if (string.contains(">=")) {
                lex_log[3]++;
            } else if (string.contains("<=")) {
                lex_log[4]++;
            }
            if (string.contains("for")) {
                lex_reserve[0]++;
            } else if (string.contains("int")) {
                lex_reserve[1]++;
            } else if (string.contains("while")) {
                lex_reserve[2]++;
            } else if (string.contains("char")) {
                lex_reserve[3]++;
            } else {
                lex_alpha++;
            }
        } while (string.endsWith(""));

1 个答案:

答案 0 :(得分:1)

试试这个:

String s = "";
        String[] words = s.split("\\s+");
        for (int i = 0; i < words.length; i++) 
        {
            switch (words[i]) 
            {
            case  "+" :
                lex_air[0]++;
                break;

            case  "-":
                lex_air[1]++;
                break;

            case  "*" : 
                lex_air[2]++;
                break;

            case  "/":
                lex_air[3]++;
                break;

            case  ">":
                lex_log[0]++;
                break;

            case  "<":
                lex_log[1]++;
                break;

            case  "=":
                lex_log[2]++;
                break;

            case  ">=":
                lex_log[3]++;
                break;

            case  "<=":
                lex_log[4]++;
                break;

            case  "for":
                lex_reserve[0]++;
                break;

            case  "int":
                lex_reserve[1]++;
                break;

            case  "while":
                lex_reserve[2]++;
                break;

            case  "char":
                lex_reserve[3]++;
                break;

            default:
                lex_alpha++;
                break;

            }
        }