"Exception in thread "main" java.util.InputMismatchException"**

445 views Asked by At

I have searched but i really can' t seem to find anything wrong in the code, please help!

The code compiles but, this is the error i get when i want to answer question 3:

Exception in thread "main" java.util.InputMismatchException
        at java.util.Scanner.throwFor(Unknown Source)
        at java.util.Scanner.next(Unknown Source)
        at java.util.Scanner.nextDouble(Unknown Source)
        at ForgetfulMachine.main(ForgetfulMachine.java:16)

And this is my code:

import java.util.Scanner;

public class ForgetfulMachine
{
    public static void main( String[] args )
    {
        Scanner keyboard = new Scanner(System.in);

        System.out.println( "What city is the capital of Germany?" );
        keyboard.next();

        System.out.println( "What is 6 divided by 2?" );
        keyboard.nextInt();

        System.out.println( "What is your favorite number between 0.0 and 1.0?" );
        keyboard.nextDouble();

        System.out.println( "Is there anything else you would like to tell me?" );
        keyboard.next();
    }
}
2

There are 2 answers

0
Radiodef On BEST ANSWER

Scanner will throw this exception if the entry is in a format that is incorrect for the Scanner's Locale. Particularly, in your case, if the wrong decimal separator is used. Both . and , are common locale-specific decimal separators.

To find out what the decimal separator is for your default locale you may use:

System.out.println(
    javax.text.DecimalFormatSymbols.getInstance().getDecimalSeparator()
);

See also:

0
Kalenda On

Nothing is wrong with your code. Respect the type when you are entering your data. Do not enter a double while you are expecting an integer, etc. You can get around this type of error by applying defensive coding where you only accept data from the user when it complies with the expected value.

public static void main(String[] arg) {
    Scanner keyboard = new Scanner(System.in);

    System.out.println( "What city is the capital of Germany?" );
    keyboard.nextLine();

    System.out.println( "What is 6 divided by 2?" );
    boolean isNotCorrect = true;

    while(isNotCorrect){
        isNotCorrect = true;
        try {
            Integer.valueOf(keyboard.nextLine());       
            isNotCorrect = false;
        } catch (NumberFormatException nfe) {
            System.out.println( "Enter an integer value" );
        }
    }


   System.out.println( "What is your favorite number between 0.0 and 1.0?" );
   isNotCorrect = true;

    while(isNotCorrect){

        try {
             Double.valueOf(keyboard.nextLine());
             isNotCorrect = false;
        } catch (NumberFormatException nfe) {
            System.out.println( "Enter a double value" );
        }
    }

    System.out.println( "Is there anything else you would like to tell me?" );
    keyboard.next();
}