“线程中的异常”main“java.util.InputMismatchException”**

时间:2014-11-19 22:25:01

标签: java inputmismatchexception

我已经搜索了但我真的可以'似乎在代码中发现任何错误,请帮助!

代码编译但是,当我想回答问题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)

这是我的代码:

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 个答案:

答案 0 :(得分:2)

如果条目的格式对于扫描程序的区域设置不正确,

Scanner将抛出此异常。特别是,在您的情况下,如果使用错误的小数分隔符。 .,都是常见的特定于语言环境的小数分隔符。

要找出您的默认语言环境的小数分隔符,您可以使用:

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

另见:

答案 1 :(得分:0)

您的代码没有任何问题。输入数据时尊重类型。在期望整数等时不要输入双精度数。 您可以通过应用防御性编码来解决此类错误,其中您只接受来自用户的数据,当它符合预期值时。

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();
}