How does input.nextInt() work exactly?

前端 未结 2 1719
南旧
南旧 2020-12-16 18:38

This is the program

public class bInputMismathcExceptionDemo {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    boole         


        
2条回答
  •  渐次进展
    2020-12-16 19:15

    The reason it is necessary here is because of what happens when the input fails.

    For example, try removing the input.nextLine() part, run the program again, and when it asks for input, enter abc and press Return

    The result will be an infinite loop. Why?

    Because nextInt() will try to read the incoming input. It will see that this input is not an integer, and will throw the exception. However, the input is not cleared. It will still be abc in the buffer. So going back to the loop will cause it to try parsing the same abc over and over.

    Using nextLine() will clear the buffer, so that the next input you read after an error is going to be the fresh input that's after the bad line you have entered.

提交回复
热议问题