javajava.util.scannerinputmismatchexception

sc.nextLine() throws InputMismatchException while sc.next() doesn't


In the following code snippet, scanner is throwing InputMismatchException after I input the value for coach and press enter. However if I use coach=sc.next(); , no such exception is thrown.

void accept() {
        System.out.println("Enter name , mobile number and coach for the customer and also the amount of ticket.");
        name=sc.nextLine();
        mobno= sc.nextLong();
        coach=sc.nextLine();
        amt=sc.nextInt();
    }

I expected no exception in both the cases however I cannot understand why the exception is thrown only for sc.nextLine();. Thanks everyone!


Solution

  • When you call sc.nextLine() to read the coach, it encounters the newline character left by the previous nextLong() call. As a result, it reads an empty line (interprets the newline character as an input line) and proceeds without letting you enter the coach name.

    My suggestion is always use nextLine() and convert to the wanted Class, like this:

    void accept() {
        System.out.println("Enter name , mobile number and coach for the customer and also the amount of ticket.");
        name = sc.nextLine();
        
        // Cast long value
        mobno = Long.valueOf(sc.nextLine());
        
        coach = sc.nextLine();
        
        // Cast int value
        amt = Integer.parseInt(sc.nextLine());
    }
    

    Check this out:

    But you can do this way too:

    void accept() {
        System.out.println("Enter name, mobile number, coach for the customer, and also the amount of ticket.");
        name = sc.nextLine();
        mobno = sc.nextLong();
    
        // Consume the remaining newline character in the input buffer
        sc.nextLine();
    
        coach = sc.nextLine();
        amt = sc.nextInt();
    }