How to test for blank line with Java Scanner?

久未见 提交于 2019-12-17 10:42:55

问题


I am expecting input with the scanner until there is nothing (i.e. when user enters a blank line). How do I achieve this?

I tried:

while (scanner.hasNext()) {
    // process input
}

But that will get me stuck in the loop


回答1:


Here's a way:

Scanner keyboard = new Scanner(System.in);
String line = null;
while(!(line = keyboard.nextLine()).isEmpty()) {
  String[] values = line.split("\\s+");
  System.out.print("entered: " + Arrays.toString(values) + "\n");
}
System.out.print("Bye!");



回答2:


From http://www.java-made-easy.com/java-scanner-help.html:

Q: What happens if I scan a blank line with Java's Scanner?

A: It depends. If you're using nextLine(), a blank line will be read in as an empty String. This means that if you were to store the blank line in a String variable, the variable would hold "". It will NOT store " " or however many spaces were placed. If you're using next(), then it will not read blank lines at all. They are completely skipped.

My guess is that nextLine() will still trigger on a blank line, since technically the Scanner will have the empty String "". So, you could check if s.nextLine().equals("")




回答3:


The problem with the suggestions to use scanner.nextLine() is that it actually returns the next line as a String. That means that any text that is there gets consumed. If you are interested in scanning the contents of that line… well, too bad! You would have to parse the contents of the returned String yourself.

A better way would be to use

while (scanner.findInLine("(?=\\S)") != null) {
    // Process the line here…
    …

    // After processing this line, advance to the next line (unless at EOF)
    if (scanner.hasNextLine()) {
        scanner.nextLine();
    } else {
        break;
    }
}

Since (?=\S) is a zero-width lookahead assertion, it will never consume any input. If it finds any non-whitespace text in the current line, it will execute the loop body.

You could omit the else break; if you are certain that the loop body will have consumed all non-whitespace text in that line already.




回答4:


AlexFZ is right, scanner.hasNext() will always be true and loop doesn't end, because there is always string input even though it is empty "".

I had a same problem and i solved it like this:

do{
    // process input
}while(line.length()!=0);
I think do-while will fit here better becasue you have to evaluate input after user has entered it.


回答5:


Scanner key = new Scanner(new File("data.txt"));
String data = "";

while(key.hasNextLine()){
    String nextLine = key.nextLine();

    data += nextLine.equals("") ? "\n" :nextLine;

}
System.out.println(data);


来源:https://stackoverflow.com/questions/7320315/how-to-test-for-blank-line-with-java-scanner

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