简体   繁体   English

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

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

I am writing a program that includes a test for whether the user input is a positive integer and displays an error messagge if the entry is a non-integer or negative. 我正在编写一个程序,其中包括用于测试用户输入是否为正整数并在条目为非整数或负数时显示错误消息的测试。 My code displays the intended error message if a non-integer is entered, but only re-prompts to enter a positive integer if a negative integer is entered. 如果输入非整数,我的代码将显示预期的错误消息,但是如果输入负整数,则仅重新提示输入正整数。 I've tried adding: 我尝试添加:

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

before 之前

 n = input.nextInt();

but that makes an error message appear even if a positive integer is entered. 但是,即使输入正整数,也会出现错误消息。

I have also tried: 我也尝试过:

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

Any help is appreciated. 任何帮助表示赞赏。

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

Try this: 尝试这个:

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

Try this: 尝试这个:

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

When the loop exits, if 'n' is still -1 you got to the end of the input, eg the user typed ctrl/d or ctrl/z depending on the platform. 当循环退出时,如果“ n”仍为-1,则到达输入的末尾,例如,根据平台,用户键入ctrl / d或ctrl / z。

If the user is at the console you might also need to skip to end of line. 如果用户在控制台上,则可能还需要跳到行尾。

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

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