I'm trying to create a while loop that iterates until the person types cat or dog. Then, the program will move on to gethering the pet's information. It's changing the variable when they type cat or dog, as per my print test, but the loop does not end.
The petType variable is set as an empty string by default.
String petType = "";
while(petType != "cat" || petType != "dog") {
System.out.println("Dog or cat? ");
petType = fetch.next().toLowerCase();
System.out.println("You typed " + petType);
}
System.out.println("type: " + petType);
I attempted to put a break in the loop:
while(petType != "cat" || petType != "dog") {
System.out.println("Dog or cat? ");
petType = fetch.next().toLowerCase();
System.out.println("You typed " + petType);
break;
}
System.out.println("type: " + petType);
But that caused the loop to end even when the answer was wrong. Placing the break outside the braces returned an error.
I also attempted this:
boolean canBoard = false;
while(canBoard = false) {
System.out.println("Pet type? ");
petType = fetch.next().toLowerCase();
System.out.println("You typed " + petType);
if(petType == "cat" || petType == "dog") {
canBoard = true;
}
}
System.out.println("type: " + petType);
However, the program sets the boolean to true without input and returned type: with no petType output.
I tried changing || to && since that was a fix from a similar question. It continued the loop.
For my final test, I returned to the original loop and changed the input to "cat"; rather than allowing user input. This caused an infinite loop. Typing either dog or cat caused the loop to continue and typing dog cat in the && loop caused the loop to repeat twice before allowing input.
I am at a loss.