Error Message Name:
InputMismatchException:
Example:
Scanner s = new Scanner(System.in); int a = s.nextInt();
When we enter 2.5 (which is not an integer) in the input window, we get the above error message.
Cause: Java is expecting one type of input (in this case, an int), while the user entered a different type (in this case, a double).
Solution: There is no fool-proof solution to this problem using concepts taught in CS125. The only measure you can take is to clearly prompt users for input so that they know exactly what the expected input type is.
Description: When reading in a primitive type using the Scanner class, followed by a reading in a String, nothing is recorded for the String value.
Example:
Scanner s = new Scanner(System.in); int p = s.nextInt(); String b = s.nextLine(); System.out.println(b);
Nothing is printed out, when we enter:
12
Hello
Cause: After reading in "12" using nextInt, the Scanner object is still on the same line of input as "12". The method nextLine would read in any characters after "12" on the same line. Since there are only empty spaces after "12", they are read in and assigned to the String b. "Hello" is not read in at all! Hence, when we print out b, empty spaces are printed out.
Solution: We need move the Scanner object to the next line, after processing "12". This is done by calling the nextLine method:
Scanner s = new Scanner(System.in); int a = s.nextInt(); s.nextLine(); //moves the scanner to the next line String b = s.nextLine(); System.out.println(b);