&引用;“线程中的异常”;“主要”;java.util.InputMismatchException“**

&引用;“线程中的异常”;“主要”;java.util.InputMismatchException“**,java,inputmismatchexception,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.nex

我已经搜索过了,但我真的没有发现代码中有任何错误,请帮助

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

你的代码没有问题。输入数据时,请尊重类型。在需要整数等时,不要输入double。 您可以通过应用防御性编码来避免这种类型的错误,在这种编码中,您只接受来自用户的符合预期值的数据

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

Scanner
如果条目的格式与Scanner的区域设置不符,则会引发此异常。特别是在您的情况下,如果使用了错误的十进制分隔符。
都是常见的特定于语言环境的十进制分隔符

要了解默认语言环境的小数分隔符,可以使用:

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


nextDouble()
之前尝试添加
nextLine()
调用您是在德国还是在用
而不是
输入浮点数的地方?尝试回答
0,5
(适合我)@zapl谢谢!是的,我在德国!