1
votes

I need to ask the user to enter a positive non-zero integer from the console that I will use as a product number in my program.

If I enter any non-integer value, the program correctly enters the while loop.

If I enter a 0 or a negative integer, the program correctly throws the exception (which I catch and handle elsewhere).

When I just press the enter key (or end of line character) it seems that the program just puts the console to another line. I want it to enter the while loop to display the error message. I think the cause is that hasNextInt() will wait until the token is a non end of line character input.

private static void validateProductNumber() throws InvalidProductNumberException { 
    Scanner keyboard = new Scanner(System.in);
    int number;
    while(!keyboard.hasNextInt()) { 
        System.out.println("Number must be an integer. Try again. ");
        System.out.println("Enter a new number: ");
        keyboard.next(); 
    }
    number = keyboard.nextInt();
    if (number <= 0)
        throw new InvalidProductNumberException();
    newNumber = number;
}

Is there another way I can implement my input validation with Scanner class so that it works correctly for all situations?

1
Bhesh Gurung's solution worked perfectly. If anyone knows another way, I would still be interested. - user1834529

1 Answers

0
votes

You can change your loop as follows:

while(true) {        
    try {
        System.out.println("Enter a new number: ");
        //read the line and parse it
        number = Integer.parseInt(keyboard.nextLine());
        break; //break the loop if the input is a valid integer
    } catch(Exception ex) {
        //print the error message if the input is incorrect
        System.out.println("Number must be an integer. Try again. ");
    }
}
if (number <= 0)
//...