2

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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.