Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is my loop set up correctly in Java?

I need to code to return two different error messages for different outputs. one for then the users input is blank and another for if the users input is not y or n. I am running in to the problem of my code returning only the error message for the not y or n because I have that message to return if the user inputs anything other than y or n. The code will return the right error message for the blank error once but then after that is gets stuck on just returning the error message for the not y or n. any suggestions on how to fix this?

while (choice.isEmpty()) 
{
    System.out.println("Error! This entery is required. Try again."); 
    choice = sc.nextLine(); 
} 

while (!(choice.equalsIgnoreCase ("y") || choice.equalsIgnoreCase ("n")))
{
    System.out.println ("Error! Please enter y, Y, n, or N. Try again ");
    choice = sc.nextLine(); 
}
like image 704
Grace Avatar asked Dec 31 '25 00:12

Grace


1 Answers

You're probably better off with one loop:

while (!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n")) {
    if (choice.isEmpty()) {
        System.out.println("Error! This entry is required. Try again.");
    } else {
        System.out.println("Error! Please enter y, Y, n, or N. Try again.");
    }

    choice = sc.nextLine(); 
}
like image 136
Robby Cornelissen Avatar answered Jan 02 '26 13:01

Robby Cornelissen