mercredi 20 septembre 2017

Moving on from a while loop to an if statement

Let's say I want this code to have the user pick one of three animals (dog, cat, pig), then have the computer reply with whatever sound the animal makes (i.e. "dog" -> "woof"). BUT, I want to be able to stop the user from entering in any other animal that isn't a dog, cat, or pig using a while statement.

When I do this, the while statement runs and loops, but if you enter "dog", it still prints "That isn't a valid animal.", when I want it to move on to the if statement below it. What's causing this?

String animal = keyboard.nextLine();

  while (!animal.equalsIgnoreCase("dog")||!animal.equalsIgnoreCase("cat")||!animal.equalsIgnoreCase("pig")) {
            System.out.println("That isn't a valid animal.");
            animal = keyboard.nextLine();

        if (animal.equals("dog"){
        System.out.println("Woof")
        }

Aucun commentaire:

Enregistrer un commentaire