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

Time:02-21

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

CodePudding user response:

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

CodePudding user response:

Try this.

if (userSelection.equals("G")) {   
    String animalGender;
            
    do {              
        String genderPrompt = "Please enter animal's gender \nMale \nFemale";
        System.out.println(genderPrompt);
        animalGender = sc.next().toLowerCase();
    } while (!animalGender.equals("male") && !animalGender.equals("female"));

     animal.setGender(animalGender);
     System.out.println("Animal Gender has been set to "   animal.getGender());                
}
  • Related