0

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

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Exception is too big a exception to be used here, just use NumberFormatException.
I tried this and got an infinite loop when a non-integer was entered.
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, e.g. the user typed ctrl/d or ctrl/z depending on the platform.

If the user is at the console you might also need to skip to end of line.

3 Comments

I tried this and the program didn't run when a positive integer was entered.
"Didn't run" meaning what exactly? It will break out of the loop above as soon as a positive number is entered.
It prompted to enter a positive integer, but when a positive integer was entered, it did not break out of the loop and print results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.