Scanner.nextLine() 实际上并没有给出下一行
我用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
比较 Java 中的字符串应使用
String#equals()
。字符串是 Java 中的对象,而不是基元。
==
将通过引用而不是值来比较对象。另请参阅:
Comparing strings in Java should be done with
String#equals()
.Strings are objects in Java, not primitives. The
==
would compare objects by reference, not by value.See also: