【问题标题】:"Exception in thread "main" java.util.InputMismatchException"**“线程“主”java.util.InputMismatchException中的异常”**
【发布时间】:2015-01-17 15:26:21
【问题描述】:

我已经搜索过,但我真的找不到代码有什么问题,请帮忙!

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

【问题讨论】:

标签: java inputmismatchexception


【解决方案1】:

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

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

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

另见:

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-23
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多