尝试使用Scanner.nextDouble()读取32.5时的InputMismatchException

时间:2017-02-15 15:18:14

标签: java

如何在Java中使用tryparce来解决下面的问题? 代码示例很有帮助。

enter image description here

enter image description here

import java.util.Scanner;

class BasicCalculator {
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        double fnum, snum, answer; // firstnumber, 2nd number, answer
        System.out.println("Enter first number: ");
        fnum = input.nextDouble();
        System.out.println("Enter 2nd number: ");
        snum = input.nextDouble();

        answer = fnum + snum;
        System.out.println(answer);
    }
}

Enter first number: 
32.5
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 basicCalculator.BasicCalculator.main(BasicCalculator.java:8)

1 个答案:

答案 0 :(得分:1)

TL; DR:useLocale(Locale.ROOT)

我运行了您的程序并输入了32.51,000,没有错误。然后我将计算机的通用格式更改为德语并再次运行。这次我看到了与你的问题相同的堆栈跟踪。接下来,我将Scanner的初始化更改为:

    Scanner input = new Scanner(System.in).useLocale(Locale.ROOT);

现在你的程序再次按照我的预期运作:

Enter first number: 
32.5
Enter 2nd number: 
1,000
1032.5