Java 扫描器 hasNextLine 返回 false
这可能更多是因为我对代码不熟悉,但我一直遇到以下问题:
我有一个包含空行的文本文件,以及一个扫描该文件的扫描仪。
当我使用 .hasNextLine() 方法时,即使文件中有更多行,它也会返回 false。我必须指出,该文件以空行开头,并且内部文本之间有更多空行,最后以空行结束。
但无论行是否有文本,它不应该返回 true 吗?
This is probably due more to my lack of familiarity with the code than anything else, but I keep having the following problem:
I have a text file that has empty lines, and a scanner that goes through the file.
When I use the .hasNextLine() method, it returns false even though there are more lines in the file. I must point out that the file begins with an empty line, and that the text inside has more empty lines in between, and finally ends with empty lines.
But shouldn't it return true regardless of whether the lines have text or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,应该的。
试试这个:
确保文件“text.txt”存在,并且其中只有回车符。然后运行这个。
Yes, it should.
Try this:
Make sure the file "text.txt" exists, and just carriage returns in it. Then run this.
使用
.hasNext()
方法而不是使用.hasNextLine()
方法。您遇到问题是因为
.hasNextLine()
方法仅当下一行包含某些内容时才返回 true。而.hasNext()
方法返回 true,即使下一行中有任何标记(此处下一行的标记为\n
)use the
.hasNext()
method instead of using the.hasNextLine()
method.You are having problems because the
.hasNextLine()
method returns true only if the next line has some content in it. Whereas the.hasNext()
method returns true even if there is any token in the next line(here the token being\n
for the next line)取自 SUN(oracles?)1.5 JDK 的源代码,任何与以下正则表达式匹配的内容都被视为“行”。这包括 Windows 或 linux/unix 下的空行。
因此,即使除回车符之外的行为空,它也应该返回 true。
Taken from the source for SUNs (oracles?) 1.5 JDK, anything which matches the following regular expression is treated as a "line". This includes empty lines under Windows or linux/unix.
So it should return true even if lines are empty except for carriage return.