Scanner.nextLine() 实际上并没有给出下一行

发布于 2024-09-14 01:22:00 字数 1030 浏览 0 评论 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 语法工作正常。但新孩子的开始标记却不是。

I've written a pretty simple recursive-descent parser in Java, but having some issues with the scanner I've attached to the file.

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

The problem is that when { is found, the method recurses, but the next line isn't actually taken (there is a next line). It just gives back the same { token, which is not valid.

I've been using a sample file to test this out:

Name = scumbag
{
    Name = lolcakes
}
}

Used reflection and I confirmed that the field=value syntax is working fine. But the opening token for a new child isn't.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

度的依靠╰つ 2024-09-21 01:22:00
if (nextline == "{") { 

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

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

字符串是 Java 中的对象,而不是基元。 == 将通过引用而不是值来比较对象。

另请参阅:

if (nextline == "{") { 

Comparing strings in Java should be done with String#equals().

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

Strings are objects in Java, not primitives. The == would compare objects by reference, not by value.

See also:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文