这是部分代码无法正常工作,不想粘贴所有代码,如果我尝试输入 3.2,它会给我“错误数据”,但如果我尝试输入 3.3,它会正常工作。所有getters/setters 要求 double,而不是 int,调试器讲述了同样的故事,我输入 3.2 的那一刻会打印出错误的数据
double fastest = 1000;
double choice1timechoice;
boolean goodTime = false;
while(!(goodTime)) {
System.out.println("Enter time of the sprint:");
try {
choice1timechoice = scan.nextDouble();
if (choice1timechoice < fastest) {
fastest = choice1timechoice;
fastIndex = numSprints;
}
sprint[numSprints].setTime(fastest);
goodTime = true;
System.out.println("Do you wish to continue adding sprints? 1 for yes, 2 for no");
cont = scan.nextInt();
if (cont == 1) numSprints++;
}
catch (InputMismatchException ex)
{
System.out.println("Bad data");
System.out.println("Please try again \n");
scan.nextLine();
}
}
最佳答案
这似乎是一个语言环境问题。根据评论,OP 系统上默认的本地小数点分隔符是 ','
而不是 '.'
。因此 Scanner
默认拒绝识别 3.2
而只识别 3,2
。
要使Scanner
接受3.2
,您可以手动设置其语言环境:
scan.useLocale(Locale.US);
关于Java,scan double只接受int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24223339/