How to test for blank line with Java Scanner?

后端 未结 5 1329
难免孤独
难免孤独 2020-12-02 23:58

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.ha         


        
5条回答
  •  情书的邮戳
    2020-12-03 00:24

    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("")

提交回复
热议问题