A working example is to have a while loop that continues to get a number from the user until they guess the number correctly, then it will return true and exit out the while loop.
However, if I create a method that returns whether the variable is true or false, the while loop does not terminate. But, if the IF condition is inside the while loop, it terminates and work as intended.
Code that Works as Intended:
private void print() { // Method name not decided yet
boolean playerGuessedCorrectly = false;
while(!playerGuessedCorrectly) {
[...] // Other code that asks the user to enter a new number
// userGuess is the next int entered by the user
// computerNumber is a random number between 1 and 100
if(userGuess == computerNumber) {
System.out.print("You have guessed my number.");
playerGuessedCorrectly = true;
} // while loop terminates upon true
}
}
This code works and the while loop stops working when it is changed to true. However, when I put the same code in a method, the while loop continues going around and does not terminate:
Not Working Code:
private void print() {
boolean playerGuessedCorrectly = false;
while(!playerGuessedCorrectly) {
checkIfGuessIsMyNumber(playerGuessedCorrectly);
} // value of playerGuessedCorrectly is sent to method checkIfGuessIsMyNumber();
private boolean checkIfGuessIsMyNumber(boolean playerGuessedCorrectly) {
// userGuess is the next int entered by the user
// computerNumber is a random number between 1 and 100
if(userGuess == computerNumber) {
System.out.print("You have guessed my number.");
return playerGuessedCorrectly = true;
} else {
playerGuessedCorrectly = false;
}
}
To clarify, the while loop terminates when IF userGuess == computerNumber is inside the while loop, however, it does not work when it is split up into a different method and returns the value.
Note that when I print out the value given by the method, it has printed true. So I am confused to why it doesn't terminate when the value in the method is true, but it terminates with the if condition inside the while loop.