-1

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!

  • 1
    What is the exact input? – dan1st Jul 26 '23 at 16:37
  • 3
    Your error description and debugging done so far aren't very detailed, [but this may be a case of nextLine() being skipped after your nextLong() call](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – OH GOD SPIDERS Jul 26 '23 at 16:41
  • Does this answer your question? [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Sören Jul 26 '23 at 18:03

1 Answers1

2

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();
}
Dmitriy Popov
  • 2,150
  • 3
  • 25
  • 34
Diego Borba
  • 1,282
  • 8
  • 22