0

我已经搜索过,但我似乎真的找不到代码中的任何错误,请帮助!

代码可以编译,但这是我想回答问题 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();
    }
}
4

2 回答 2

2

Scanner如果条目的格式对于扫描程序的区域设置不正确,则将引发此异常。特别是,在您的情况下,如果使用了错误的小数分隔符。两者.,都是常见的特定于语言环境的小数分隔符。

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

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

也可以看看:

于 2014-11-19T23:57:30.587 回答
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();
}    
于 2014-11-19T22:43:30.830 回答