简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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