【发布时间】:2012-08-30 00:27:57
【问题描述】:
这是我的 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
}
}
你可以从 cmets 看到这应该做什么。
但是当我输入不是数字的东西时,就会发生这种情况:
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。
【问题讨论】:
-
不要抓
Throwable,而是抓具体的InputMismatchException。 -
旁白:在 Python 中,您可能应该使用
ValueError而不是Exception。
标签: java python loops while-loop nan