How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner

前端 未结 5 1932
南方客
南方客 2020-11-21 06:30

So, I\'m getting stuck with this piece of code:

import java.util.InputMismatchException;
import java.util.Scanner;

public class ConsoleReader {

    Scanner         


        
5条回答
  •  离开以前
    2020-11-21 07:03

    As per the javadoc for Scanner:

    When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

    That means that if the next token is not an int, it throws the InputMismatchException, but the token stays there. So on the next iteration of the loop, reader.nextInt() reads the same token again and throws the exception again. What you need is to use it up. Add a reader.next() inside your catch to consume the token, which is invalid and needs to be discarded.

    ...
    } catch (InputMismatchException e) {
        System.out.println("Invalid value!");
        reader.next(); // this consumes the invalid token
    } 
    

提交回复
热议问题