Scanner.hasNextLine – 总是为真

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

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)

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:

确定