How to test for blank line with Java Scanner?

后端 未结 5 1328
难免孤独
难免孤独 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:36

    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.

提交回复
热议问题