Java Scanner.nextxxx() related exception handling

Posted by freedomclan on Mon, 07 Feb 2022 09:08:37 +0100

The situations encountered are as follows

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int i;
    try {
        System.out.println("Please enter an integer value");
        i = input.nextInt();
        System.out.println("i:" + i);
    } catch (InputMismatchException e) {
        e.printStackTrace();
        System.out.println("Input format mismatch");
    }
}

The above code creates a new input reference variable and references it to the Scanner, try module through input Nextint() gets an integer value.
For the try module, if the user normally inputs some integers through the console, the program will run normally. However, if the user inputs something that is not all integers through the console, such as sfs1321, the catch module will catch an exception of inputmismatch exception, which means that the input format does not match the expected one.

So, what does Scanner store in memory after capturing the exception of inputmismatch exception? See the following code:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int i;
    try {
        System.out.println("Please enter an integer value");
        i = input.nextInt();
        System.out.println("i:" + i);
    } catch (InputMismatchException e) {
        e.printStackTrace();
        System.out.println("Input format mismatch");
    } finally {
        System.out.println(input.next());
    }
}

In the above code, I added a finally module after catch and passed it internally through input Next () outputs something cached in Scanner memory.
The operation effect is as follows;

It can be seen that when the catch module catches the inputmismatch exception of the Scanner input, the last input data will be temporarily stored in the memory buffer of the Scanner.

Some little things: validation format input loop code

Original code with problem:

Scanner input = new Scanner(System.in);
int id = 0;
while (true) {
    try {
        System.out.println("Please enter ID");
        id = input.nextInt();
        System.out.println("id:" + id);
        break;
    } catch (InputMismatchException e) {
        e.printStackTrace();
        System.out.println("Input format mismatch");
    }
}

When the integer is input normally, the program runs normally.
When the input is not all integers, the code will loop indefinitely and skip the try module every time from the second loop.

The reasons for this problem are as follows:
Combined with the situation encountered, what is introduced in the chapter. After receiving any input, the Scanner will temporarily save the data to the memory cache, and then pass it to the required nextxxx() function through the memory cache.
When inputting a data that is not all integers, because this data format is different from input The integer format required by nextint () is different, so the data in the memory cache will not be passed to netInt(). Meanwhile, catch catches the inputmismatch exception and executes the code of catch module. In the second cycle, because there is still data in the memory buffer of Scanner, the data in the memory buffer is directly passed to nextInt(), and then the exception of inputmismatch exception is thrown, so it goes on indefinitely.

terms of settlement:
The change code is as follows:

public static void main(String[] args) {
   Scanner input = new Scanner(System.in);
   int id = 0;
   while (true) {
       try {
           System.out.println("Please enter ID");
           id = input.nextInt();
           System.out.println("id:" + id);
           break;
       } catch (InputMismatchException e) {
           e.printStackTrace();
           input.next();
           System.out.println("Input format mismatch");
       }
   }
}

Note:

For methods such as nextInt() next() nextFloat(), after obtaining the data of Scanner's memory cache, the cursor will stay at the end of the current line without passing '\ n' to the method.

After the cursor of the method 'next' stays on the top of the new line of memory, it will also pass the cursor to the method 'next'.

Recommendations:

When using Scanner for input, if you use different methods twice, such as using input for the first time Nextint(), and then use input a second time When nextfloat(), it is recommended to add input. In between Nextline() to empty Scanner's memory cache.

Xiaobai understands. If there is any mistake, welcome to discuss it.

Topics: Java