I believe I wrote all my code correctly but Im getting this error, can someone help me understand:
Exception in thread "main" java.util.InputMismatchException at java.base/java.util.Scanner.throwFor(Scanner.java:939) at java.base/java.util.Scanner.next(Scanner.java:1594) at java.base/java.util.Scanner.nextDouble(Scanner.java:2564) at gangPackage.newClass.main(newClass.java:15)
Here is my code:
package gangPackage; import java.util.*; public class newClass { public static void main (String[] args) { Scanner Scan = new Scanner(System.in); String name; int age; double gpa; System.out.println("Enter your name: "); name = Scan.nextLine(); System.out.println("Enter students age: "); age = Scan.nextInt(); System.out.println("Enter your GPA: "); gpa = Scan.nextDouble(); System.out.printf(name + " is " + age + " years old. And has a GPA of " + gpa); } }
Advertisement
Answer
Your code looks OK.
An InputMismatchException
occurs in a Scanner
when a given input doesn’t match the expected input format. Your exception occurs on line 15, where a scanner expects a decimal number such as 3.14
(which, depending on your system’s locale, the decimal can be represented by a dot .
or a comma ,
!)
If you’re certain that the input you’re providing is absolutely a decimal number, but you’re not sure what locale you’re using, you can force a particular locale by using the useLocale
method.
Scanner Scan = new Scanner(System.in).useLocale(Locale.US);