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.
The issue you are facing is related to the condition in the while loop. The condition petType != "cat" || petType != "dog" will always evaluate to true because petType cannot be both "cat" and "dog" at the same time. So, the loop will continue indefinitely.
To fix this, you need to use the logical AND (&&) operator instead of the logical OR (||) operator in your loop condition. Additionally, when comparing strings, you should use the equals() method instead of ==, as == checks for reference equality, not the content of the strings.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner fetch = new Scanner(System.in);
String petType = "";
while (!petType.equals("cat") && !petType.equals("dog")) {
System.out.println("Dog or cat? ");
petType = fetch.next().toLowerCase();
System.out.println("You typed " + petType);
}
System.out.println("Type: " + petType);
}
}
Now, the loop will keep asking for the pet type until the user types "cat" or "dog". Once the user inputs either "cat" or "dog", the loop will exit, and the program will proceed to the next part where you gather the pet's information. The equals() method ensures that the content of the strings is compared properly, and the loop behaves as expected.