Java Scanner won't “finish” reading input

前端 未结 4 1626
不思量自难忘°
不思量自难忘° 2021-01-14 17:09

I\'ve been having trouble using java\'s Scanner class. I can get it to read my input just fine, but the problem is when I want to output something. Given multiple lines of i

4条回答
  •  一向
    一向 (楼主)
    2021-01-14 17:42

    As I can see in your outer while loop you have used

    scanner.hasNextLine();
    

    method. This method gets blocked if it has to wait for the input. Also you have

    Scanner scanner = new Scanner(System.in);
    

    statement. So the system.in will be waiting for input all the time, hence the hasNextLine() method has to wait for the input. That is why the control gets stuck in the loop and can't proceed further.

    To fix it you can first store input in a string variable and the call the scanner constructor on it.

提交回复
热议问题