代码之家  ›  专栏  ›  技术社区  ›  Puppy

scanner.next line()实际上没有给出下一行

  •  0
  • Puppy  · 技术社区  · 14 年前

    我在Java中编写了一个非常简单的递归下降分析器,但是在我连接到文件的扫描器上有一些问题。

    private void ParseDataFields(Controller.TreeData data, java.util.Scanner scanner) {
            java.lang.String nextline;
            while(scanner.hasNextLine()) {
                nextline = scanner.nextLine().trim();
                if (nextline == "{") { // If we are with this, we are a new Child object declaration.
                    if (data.CanHaveChildren()) {
                        ParseDataFields(data.CreateNewChild(), scanner);
                        continue;
                    } else
                        FileValidationError("Attempted to give a child object to a data node that could not have one.");
                }
                if (nextline.endsWith("}")) // End of Child object data declaration
                    return;
                ... parse the line
    

    问题是,当找到时,该方法会重复出现,但实际上没有采用下一行(有下一行)。它只是返回相同的令牌,这是无效的。

    我一直在用一个示例文件来测试这个问题:

    Name = scumbag
    {
        Name = lolcakes
    }
    }
    

    使用反射,我确认field=value语法工作正常。但新孩子的开场白不是。

    1 回复  |  直到 13 年前
        1
  •  2
  •   Community pid    7 年前
    if (nextline == "{") { 
    

    比较Java中的字符串应该用 String#equals() .

    if (nextline.equals("{")) {
    

    字符串是Java中的对象,而不是基元。这个 == 将按引用而不是按值比较对象。

    参见: