0

我用 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 语法工作正常。但新孩子的开放令牌不是。

4

1 回答 1

2
if (nextline == "{") { 

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

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

字符串是 Java 中的对象,而不是原语。将按引用而==不是按值比较对象。

也可以看看:

于 2010-08-11T12:08:54.697 回答