Java while loop error printing user input requires enter key to be pressed twice

Viewed 72

i'm trying to print out the invalid input entered by a user, but am running in to problems if they enter some long text containing spaces a second time ..... it requires enter key to be pressed twice before the error message is printed. Below is code i have done for it any idea how to fix it?

private Scanner input;
input = new Scanner(System.in);
while (!input.hasNextInt()) {
    System.out.println("[ERROR] Invalid entry!" + input.nextLine() 
        + "\n Please enter a valid Menu Option number ");
    input.nextLine();
}
2 Answers

You have two input.nextLine() in while loop; one in print statement, one after print method, this is why you need press enter twice. Try using below code:

    Scanner input;
    input = new Scanner(System.in);
    while (!input.hasNextInt()) {
        String s = input.nextLine();
        System.out.println("[ERROR] Invalid entry!"  + s + "\n Please enter a valid Menu Option number ");
    }

Instead of using input.nextLine() in your print statement, get the input once and store it to use.

Try to change the while loop into an if statement like that:

Scanner input;
input = new Scanner(System.in);
if (!input.hasNextInt()) {
    String myString = input.nextLine();
    System.out.println("[ERROR] Invalid entry!"  + myString + "\n Please enter a valid Menu Option number ");
}

You don't need to check every time if the input has an integer value, because the if statement will only check the condition when the user enters an input

Related