如何使用 Java Scanner 测试空行?
我期待用扫描仪输入,直到没有任何内容(即当用户输入空行时)。我该如何实现这一目标?
我尝试过:
while (scanner.hasNext()) {
// process input
}
但这会让我陷入困境
I am expecting input with the scanner until there is nothing (i.e. when user enters a blank line). How do I achieve this?
I tried:
while (scanner.hasNext()) {
// process input
}
But that will get me stuck in the loop
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个方法:
Here's a way:
来自 http://www.java-made-easy.com/java-扫描仪帮助.html:
我的猜测是
nextLine()
仍会在空行上触发,因为从技术上讲,扫描仪将具有空字符串""
。因此,您可以检查if s.nextLine().equals("")
From http://www.java-made-easy.com/java-scanner-help.html:
My guess is that
nextLine()
will still trigger on a blank line, since technically the Scanner will have the empty String""
. So, you could checkif s.nextLine().equals("")
使用
scanner.nextLine()
的建议的问题在于它实际上以String
形式返回下一行。这意味着那里的任何文本都会被消耗。如果您有兴趣扫描该行的内容……那么,太糟糕了!您必须自己解析返回的String
内容。更好的方法是使用
由于
(?=\S)
是零宽度先行断言,因此它永远不会消耗任何输入。如果它在当前行中找到任何非空白文本,它将执行循环体。如果您确定循环体已经消耗了该行中的所有非空白文本,则可以省略
else break;
。The problem with the suggestions to use
scanner.nextLine()
is that it actually returns the next line as aString
. That means that any text that is there gets consumed. If you are interested in scanning the contents of that line… well, too bad! You would have to parse the contents of the returnedString
yourself.A better way would be to use
Since
(?=\S)
is a zero-width lookahead assertion, it will never consume any input. If it finds any non-whitespace text in the current line, it will execute the loop body.You could omit the
else break;
if you are certain that the loop body will have consumed all non-whitespace text in that line already.AlexFZ 是对的,
scanner.hasNext()
将始终为 true 并且循环不会结束,因为即使它是空的“”,也总是有字符串输入。我有同样的问题,我是这样解决的:
I think
do-while
will fit here better becasue you have to evaluate input after user has entered it.AlexFZ is right,
scanner.hasNext()
will always be true and loop doesn't end, because there is always string input even though it is empty "".I had a same problem and i solved it like this:
I think
do-while
will fit here better becasue you have to evaluate input after user has entered it.