Scanner.hasNextLine – 总是为真

huangapple go评论76阅读模式
英文:

Scanner.hasNextLine - always true

问题

我需要从标准输入读取数据。
并且我想将它打印到标准输出。
我使用Scanner来实现这个目标:

  1. import java.util.Scanner;
  2. public static void main(String[] args) {
  3. Scanner scanner = new Scanner(System.in);
  4. StringBuilder sb = new StringBuilder();
  5. int countLines = 1;
  6. while (scanner.hasNextLine()) {
  7. String line = scanner.nextLine();
  8. sb.append(countLines).append(" ").append(line);
  9. }
  10. System.out.println("finish");
  11. System.out.println(sb.toString());
  12. scanner.close();
  13. }

我输入了以下数据:

  1. Hello world
  2. I am a file
  3. 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:

  1. import java.util.Scanner;
  2. public static void main(String[] args) {
  3. Scanner scanner = new Scanner(System.in);
  4. StringBuilder sb = new StringBuilder();
  5. int countLines = 1;
  6. while (scanner.hasNextLine()) {
  7. String line = scanner.nextLine();
  8. sb.append(countLines).append(" ").append(line);
  9. }
  10. System.out.println("finish");
  11. System.out.println(sb.toString());
  12. scanner.close();
  13. }

I input this data:

  1. Hello world
  2. I am a file
  3. 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

  1. while(scanner.hasNextLine())
  2. {
  3. String line = scanner.nextLine();
  4. if(line.equalsIgnoreCase("stop"))
  5. {
  6. break;
  7. }
  8. //whatever else you have in the loop
  9. }

除非你停止它,它会一直为真。正如 @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"

  1. while(scanner.hasNextLine())
  2. {
  3. String line = scanner.nextLine();
  4. if(line.equalsIgnoreCase("stop"))
  5. {
  6. break;
  7. }
  8. //whatever else you have in the loop
  9. }

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)

huangapple
  • 本文由 发表于 2020年8月30日 06:36:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63652404.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定