1

我正在写一个词法分析器。我有一个开关结构,这是该区域出现的代码片段。

    //whitespace
    case ' ':
    case '\t':
    case '\n':
        consume(); System.out.println("consumed ws");
        break;

    //identifier
    default:
        if (isLetter()) {
            consume();
            state = 8;
        } else {
            System.out.println("invalid character: " + look);
        }
        break;

问题是,虽然它会正确使用空格和制表符,但它不会使用换行符,而是使用默认值。

我在其他地方与 '\n' 进行了比较,它们工作正常。例如,如果注释掉了一行,则执行以下代码:

            case 10:
                while(look != '\n'){
                    consume();
                }
                consume();
                state = 0;
            break;

所以看起来它只是在 switch 结构中的错误,而不是 if 或 while 语句。但是,如果我在默认情况下添加一些处理换行符的内容,则将 (look == '\n') 评估为 true,即使我打印出外观,它也会在输出中创建一个新行。

4

2 回答 2

2

Are you using MS Windows? If yes, the end line in Windows is \r\n. But in Linux your program should be OK.

You should ignore \r character by adding another case for \r to do nothing!

于 2013-03-29T21:17:48.050 回答
0

boomz answer is correct. I just had to add a under whitespace where the case is '\r'.

    //whitespace
    case ' ':
    case '\t':
    case '\r':
    case '\n':
        consume();
        break;

Keep in mind that all consume() does is get another character, so nothing else is done here.

Thanks.

于 2013-03-29T21:31:19.433 回答