I'm new here, and to code in general. What I'm trying to accomplish is to create a simple guessing game that prompts a user for a number, and checks that number against a computer generated number between 1 and 100. I've tried to make it so the player can continue guessing until they get the correct answer, as well as display a counter to let the player know how many guessing attempts they have made. The problem is, the program won't terminate after the correct answer has been given, and I can't figure out what I'm doing wrong. I'll paste the entire code at the bottom for reference, but I feel like the problem lies within the following statement in the "determineAnswer" method:
} else if (userAnswer == computerNumber) {
message = "Correct"
+ "\nNumber of Guesses: " + count;
success++;
I'm trying to use the value of the integer "success" as the condition to terminate the do/while loop, but even though I try to increment the value, the loop continues as if the value is being continuously reset. If that's the case, I can't see where I've gone wrong. Again, I'm quite new at this but I would appreciate any input.
import javax.swing.JOptionPane;
public class GuessingGame {
public static void main(String[] args) {
// generate a random number from 1 to 100
int computerNumber = (int) (Math.random() * 100 + 1);
// declare other variables
int success = 0;
int count = 0;
// display the correct guess for testing purposes
System.out.println("The correct guess would be " + computerNumber);
// prompt user for a guess
do {
count++;
String response = JOptionPane.showInputDialog(null,
"Enter a guess between 1 and 100");
int userAnswer = Integer.parseInt(response);
// display result
JOptionPane.showMessageDialog(null, determineGuess(userAnswer, computerNumber, success, count));
} while (success == 0);
}
public static String determineGuess(int userAnswer, int computerNumber,int success, int count) {
String message = null;
if (userAnswer <= 0 || userAnswer > 100) {
message = "Invalid guess"
+ "\nNumber of Guesses: " + count;
} else if (userAnswer == computerNumber) {
message = "Correct"
+ "\nNumber of Guesses: " + count;
success++;
} else if (userAnswer > computerNumber) {
message = "Incorrect, Too High"
+ "\nNumber of Guesses: " + count;
} else if (userAnswer < computerNumber) {
message = "Incorrect, Too Low"
+ "\nNumber of Guesses: " + count;
}
return message;
}
}