5

I believe I wrote all my code correctly but I'm 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);
    }
}
8
  • 4
    What were your inputs? Commented Mar 5, 2019 at 4:27
  • Your code is correct. I think the input during GPA (line 15, as what the error says) are not in double format, maybe you entered a non number input Commented Mar 5, 2019 at 4:29
  • @Mark My Inputs were: Hotam for the name 19 for the age, and 3.9 for the GPA, when i put a single digit in the GPA it runs fine. and even adds a 0 at the end for example If i put 3, it will print 3.0 Commented Mar 5, 2019 at 4:30
  • I think you need to add some more code to check input. try to use Scanner.hasNext...() method. Commented Mar 5, 2019 at 4:31
  • 1
    I executed your code with your input. It works well, no error was thrown Commented Mar 5, 2019 at 4:34

2 Answers 2

6

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);
Sign up to request clarification or add additional context in comments.

Comments

-3

when you enter a double or a float, enter with a comma (,) not a period (.) when the console asks you to enter a value.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.