Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...