英文:
Scanner.hasNextLine - always true
问题
我需要从标准输入读取数据。
并且我想将它打印到标准输出。
我使用Scanner来实现这个目标:
import java.util.Scanner;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
int countLines = 1;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
sb.append(countLines).append(" ").append(line);
}
System.out.println("finish");
System.out.println(sb.toString());
scanner.close();
}
我输入了以下数据:
Hello world
I am a file
Read me until end-of-file.
但是hasNextLine())
总是true。因此永远不会打印"finish"。
英文:
I need to read data from standard input.
And I want to print it to standard output.
I use Scanner for this:
import java.util.Scanner;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
int countLines = 1;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
sb.append(countLines).append(" ").append(line);
}
System.out.println("finish");
System.out.println(sb.toString());
scanner.close();
}
I input this data:
Hello world
I am a file
Read me until end-of-file.
But hasNextLine())
is always true. And as result never print "finish"
答案1
得分: 2
你的代码似乎工作正常。你确定已经正确输出了 EOF 吗?尝试按 Ctrl+D(Mac 上为 Cmd+D)或者在 Windows 上按 Ctrl+Z,就像这里提到的一样:如何通过 Windows 终端发送 EOF
英文:
Your code seems to work fine. Are you sure you output EOF correctly? Try Ctrl+D (Cmd+D on Mac) or Ctrl+Z on Windows, as mentioned here: How to send EOF via Windows terminal
答案2
得分: 1
while(scanner.hasNextLine())
{
String line = scanner.nextLine();
if(line.equalsIgnoreCase("stop"))
{
break;
}
//whatever else you have in the loop
}
除非你停止它,它会一直为真。正如 @Aaron 指出的那样:
Scanner.hasNextLine() 会阻塞等待新的一行,只有在你关闭流(使用 Ctrl-Z 或 D,就像 Liel 在他的回答中提到的)时,它才会返回 false。
英文:
There is no condition in which the loop will be false, it'll read the lines forever and ever. Consider adding a stop keyword like "stop"
while(scanner.hasNextLine())
{
String line = scanner.nextLine();
if(line.equalsIgnoreCase("stop"))
{
break;
}
//whatever else you have in the loop
}
Unless you stop it, it'll always be true. As pointed out by @Aaron
> Scanner.hasNextLine() blocks waiting for a new line, it will only return false if you close the stream (using Ctrl-Z or D as Liel mentions in his answer)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论