Search code examples
javaexceptionjava.util.scannerinputmismatchexception

InputMismatchException with Scanner


I have the following Java code:

Scanner input = new Scanner(System.in);
    try {
        System.out.println("Enter your name>>");
        String name = input.next();
        System.out.println("Enter your year of birth>>");
        int age = input.nextInt();

        System.out.println("Name:  " + name);
        System.out.println("Year of Birth:  " + age);
        System.out.println("Age:  " + (2012 - age));

    } catch (InputMismatchException err) {
        System.out.println("Not a number");
    }

When I enter a name with a space (e.g. "James Peterson"), I get the next line output correctly (Enter your year of birth) and then an InputMismatchException immediately. The code works with a single name without spaces. Is there something I'm missing?


Solution

  •     System.out.println("Enter your name>>");
        String name = input.next();
        System.out.println("Enter your year of birth>>");
        int age = input.nextInt();
    

    Scanner, breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

    When you enter "James Peterson", Scanner#next() takes "James" as a token and assigns it to String name and then you do a Scanner#nextInt() which takes "Peterson" as the next token, but it is not something which can be cast to int and hence the InputMismatchException asnextInt() will throw an InputMismatchException if the next token does not match the Integer regular expression, or is out of range.