Java : How to use scanner.hasNextLine without Ctrl+Z in a console program

亡梦爱人 提交于 2019-12-13 08:07:14

问题


Say I have the below code

Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
     line = scanner.nextLine();
     //do something
    }

And my input in the console is goes like this.

Wayne Rooney
Luis Nani
Shinji Kagawa

I want to read this line by line.

But the problem is the method hasNextLine blocks waiting for the input after the third line as the input from the keyboard (System.in) never reaches EOF.

Now, how do I reach EOF just by pressing enter key? because I don't want to tell the user to press the Ctrl+z to run my program.

How is it generally done? Any thoughts?

I am looking for a solution from the Java side and not any commands on the console.

Thanks in advance


回答1:


How is it generally done?: It is usually done by showing a message to the user and requesting some special word to finish the input.

public static void main(String[] args) throws IOException
{
    Scanner scanner = new Scanner(System.in);
    String line;

    System.out.println("Enter names (\"QUIT\" to finish)");
    while (scanner.hasNextLine()) {
        line = scanner.nextLine();
        if (line.equals("QUIT")) {
            break;
        }
    }
    // ...
}

In the example above the special word used is "QUIT", of course you will change this to a more appropriated one.




回答2:


When you press enter twice, you end up reading an empty line. You can test for this:

while (scanner.hasNextLine()) {
    line = scanner.nextLine();
    if (line.equals(""))
        break; // this will exit the loop
    //do something
}

Now, the loop will end if you press enter twice without typing anything between.



来源:https://stackoverflow.com/questions/21246472/java-how-to-use-scanner-hasnextline-without-ctrlz-in-a-console-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!