Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How would I return to the input in this while loop?

I’m trying to get this to loop back to the input if the input is invalid.

if(userSelection == 'G') {
     String genderPrompt = "Please enter animal's gender\n" + "Male\n" + "Female";
     System.out.println(genderPrompt);
     String animalGender = readInput.nextLine().toLowerCase();
                    
     System.out.println(animalGender);
                    
     while(!animalGender.equals("male") && !animalGender.equals("female")) {
          System.out.println("Invalid Selection.");
          System.out.println(genderPrompt);
     }
                    
     animal.setGender(animalGender);
     System.out.println("Animal Gender has been set to " + animal.getGender());

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Remember that when you create a while loop, you need to edit or update the variable so that the condition will eventually become false, otherwise the loop will continue infinitely.

Since your while loop runs depending on the value of animalGender, it would make sense to update animalGender by taking in user input inside the while loop. By doing this, if the user’s animalGender is invalid, we output that there is an error and ask them for another input:

while (!animalGender.equals("male") && !animalGender.equals("female")) {
    System.out.println("Invalid Selection.");
    System.out.println(genderPrompt);
    animalGender = readInput.nextLine().toLowerCase();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading