如何在Java中使用tryparce来解决下面的问题? 代码示例很有帮助。
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)
答案 0 :(得分:1)
TL; DR:useLocale(Locale.ROOT)
。
我运行了您的程序并输入了32.5
和1,000
,没有错误。然后我将计算机的通用格式更改为德语并再次运行。这次我看到了与你的问题相同的堆栈跟踪。接下来,我将Scanner
的初始化更改为:
Scanner input = new Scanner(System.in).useLocale(Locale.ROOT);
现在你的程序再次按照我的预期运作:
Enter first number:
32.5
Enter 2nd number:
1,000
1032.5