我正在试图弄清楚为什么我的程序正在跳过用户输入,所以我可以想出一个解决方案。如果我故意给它输入错误并导致抛出InputMismatchException,它会跳过inputDouble = in.nextDouble();
行。这是输出的样子:
Please enter floating point value or -1 to stop
15.7
Please enter floating point value or -1 to stop
15.7
Please enter floating point value or -1 to stop
r
Number format is incorrect please try again
Please enter floating point value or -1 to stop
Number format is incorrect please try again
Total is: 31.4
这是我的代码
import java.util.InputMismatchException;
import java.util.Scanner;
public class AddingNumbers {
public static void main(final String[] args) {
Scanner in = new Scanner(System.in);
double inputDouble = 0;
double total = 0;
int tries = 0;
boolean done = false;
while (!done) {
if (tries < 2) {
try {
System.out.println("Please enter floating point value or -1 to stop");
inputDouble = in.nextDouble();
if (inputDouble != -1) {
total = total + inputDouble;
} else {
System.out.println("Total is: " + total);
done = true;
}
} catch (InputMismatchException exception) {
System.out.println("Number format is incorrect please try again");
tries++;
}
} else {
System.out.println("Total is: " + total);
done = true;
}
}
in.close();
}
}
答案 0 :(得分:0)
您可以尝试在in.nextLine();
inputDouble=in.nextDouble();
答案 1 :(得分:0)
扫描仪仍然在缓冲区中输入无效。要清除&#34;清除&#34;您需要使用in.nextLine();
的缓冲区。在in.nextLine();
之后使用tries++
来解决您的问题。