0

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

4

4 回答 4

2

在块中调用nextLine()方法。catch

将此扫描器前进到当前行并返回被跳过的输入。此方法返回当前行的其余部分,不包括末尾的任何行分隔符。位置设置为下一行的开头。

由于此方法继续搜索输入以查找行分隔符,因此如果不存在行分隔符,它可能会缓冲所有搜索要跳过的行的输入。

 catch (InputMismatchException t) { // on error
    userInput.nextLine();
    System.out.println("NaN"); // not a number
  }
于 2012-09-05T10:04:30.967 回答
1
while (true) { // forever loop
    try {
        scanner userInput = new Scanner(System.in); 
        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
    }
}

您应该在 while 循环中使用扫描器类,然后如果给定的输入值错误,它只会询问下一个输入值。

于 2012-09-05T10:04:49.987 回答
0

As above , You can change it like this:

    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
            userInput.nextLine();
        }
    }
于 2012-09-05T10:51:34.010 回答
0

尝试这个,

double n;
boolean is_valid;

do {
    try {
        System.out.print("Please type a value: ");
        Scanner kbd = new Scanner(System.in);
        n = kbd.nextDouble();
        is_valid = true;
    } catch (Exception e) {
        System.out.println("NaN"); 
        is_valid = false;
    }
} 
while (!is_valid);
于 2012-09-05T10:10:46.330 回答