gpt4 book ai didi

Java - 用户输入 - 错误循环

转载 作者:行者123 更新时间:2023-12-02 00:13:40 25 4
gpt4 key购买 nike

这是我的 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

最佳答案

调用nextLine() catch block 中的方法。

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.

 catch (InputMismatchException t) { // on error
userInput.nextLine();
System.out.println("NaN"); // not a number
}

关于Java - 用户输入 - 错误循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12278837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com