繁体   English   中英

使用hasNextInt和do-while循环,对于负整数没有错误消息

[英]Using hasNextInt with do-while loop, no error message for negative integer

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

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);

尝试这个:

int n = -1;
while (input.hasNextInt() && (n = input.nextInt()) < 0)
{
    // print error message about negative number
}

当循环退出时,如果“ n”仍为-1,则到达输入的末尾,例如,根据平台,用户键入ctrl / d或ctrl / z。

如果用户在控制台上,则可能还需要跳到行尾。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM