这是我的Java代码:
Scanner userInput = new Scanner(System.in);
while (true) { // forever loop
try {
System.out.print("Please type a value: "); // asks user for input
double n = userInput.nextDouble(); // gets user input as a double
break; // ends if no error
}
catch (Throwable t) { // on error
System.out.println("NaN"); // not a number
}
}
您可以从评论中看到这应该做什么。
但是当我输入不是数字的东西时,会发生这种情况:
Please type a value: abc
NaN
Please type a value: NaN
Please type a value: NaN
Please type a value: NaN
Please type a value: NaN
Please type a value: NaN
Please type a value: NaN
依此类推,直到我强制停止它。
在 Python 中,我会这样做:
while True:
try:
n = float(raw_input("Please type a value: "))
break
except Exception:
print "NaN"
我如何在 Java 中做到这一点?我试过使用do while
.