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();
}
}
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.
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:
See also:
Scanner#locale()
Scanner#useLocale(Locale)
DecimalFormatSymbols#getInstance(Locale)