Search code examples
javajava.util.scannerinputmismatchexception

Why there is an InputMismatchException in my code


     System.out.print("Input the number of persons: ");
     Scanner scanner = new Scanner(System.in);
     int noOfP = scanner.nextInt();

     Person[] person = new Person[noOfP];

     String name;
     int age;
     for(int i = 0; i < person.length; i++){
        System.out.println("Input name for guest: ");
        name = scanner.nextLine();
        System.out.println("Input age for guest: ");
        age = scanner.nextInt();

        person[i] = new Person(name,age);
     }

I just wanted to initialize the Person array and set the name and age, but it throws an InputMismatchException at line age = scanner.nextInt();


Solution

  • When you ask for the number of persons, the user isn't just typing a number, they're also inserting a line terminator into the input stream. So when you ask for the name, you're not getting the name, you're getting the line terminator just before the name. And then when you do the .nextInt() for the age, you're finally getting the name. So the first thing you need to do is add scanner.nextLine() after you read the value of noOfP to skip that line terminator. That will fix things through the age of the first person. And then things will start breaking again.

    You do the same thing when you ask for age: you invoke scanner.nextInt(), leaving another line terminator in the stream. You need another scanner.nextLine() after that so things don't blow up on the second person.

    The code will look like this:

    System.out.print("Input the number of persons: ");
    Scanner scanner = new Scanner(System.in);
    int noOfP = scanner.nextInt();
    scanner.nextLine();
    
    Person[] person = new Person[noOfP];
    
    String name;
    int age;
    for(int i = 0; i < person.length; i++){
        System.out.println("Input name for guest: ");
        name = scanner.nextLine();
        System.out.println("Input age for guest: ");
        age = scanner.nextInt();
        scanner.nextLine();
    
        person[i] = new Person(name,age);
    }