java - 将 hasNextInt 与 do-while 循环一起使用,负整数不会出现错误消息

标签 java java.util.scanner do-while

我正在编写一个程序,其中包括测试用户输入是否为正整数,并在输入为非整数或负数时显示错误消息。如果输入非整数,我的代码会显示预期的错误消息,但如果输入负整数,则仅重新提示输入正整数。我尝试添加:

if (n <= 0);
System.out.print("You have not entered a positive integer"); 

之前

 n = input.nextInt();

但是即使输入正整数也会出现错误消息。

我也尝试过:

while (!input.hasNextInt() && n <= 0)

感谢任何帮助。

        Scanner input = new Scanner( System.in );
        int n = 0;

        do {
        System.out.print("Please enter a positive integer: ");
        while (!input.hasNextInt()){
            System.out.print("You have not entered a positive integer. \nPlease enter a positive integer: ");
            input.next();
        }
        n = input.nextInt();

        } while (n <= 0);

最佳答案

试试这个:

int n = -1;//<-- it won't allow user to skip the loop after first pass without proper input
do {
    System.out.print("Please enter a positive integer: ");
    try {
        n = input.nextInt();//<-- in one pass ask input from user only once
        if(0 > n) {
            System.out.print("You have not entered a positive integer. \nPlease enter a positive integer: ");
        }
    } catch (NumberFormatException ex) {
        System.out.println("Invalid number !");
        break;//<-- break loop here, if don't wana prompt user for next input
    } catch(java.util.InputMismatchException ex) {
        System.out.println("Oops number is required !");
        break;//<-- break loop here, if don't wana prompt user for next input
    }
} while (n <= 0);

关于java - 将 hasNextInt 与 do-while 循环一起使用,负整数不会出现错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24718960/

相关文章:

java - 接收 Google Cloud Endpoints 204 无内容,直至关闭 - 重新启动

java - BufferedReader 字符串内存泄漏?

Java do while not 0 or 1

java - java动态连接任意access数据库

java - 如何重新分配已输入的基于扫描仪的值? - java

java - Java 中的扫描器不工作

java - 我试图找到元音然后添加它们,但我这样做对吗?

c - 是否可以嵌套条件语句?

java - 如何以新值退出 while 循环?

java - 树集仅打印一个元素,并且应按升序获取名称