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!
When you call
sc.nextLine()to read the coach, it encounters the newline character left by the previousnextLong()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 wantedClass, like this:Check this out:
But you can do this way too: