Question: Guessing Game with a Loop import javax.swing.JOptionPane; public class GuessingGame { public static void main(String[] args) { int computerNumber = (int) (Math.random() * 100 +
Guessing Game with a Loop
import javax.swing.JOptionPane;
public class GuessingGame { public static void main(String[] args) { int computerNumber = (int) (Math.random() * 100 + 1); System.out.println("The correct guess would be " + computerNumber); String response = JOptionPane.showInputDialog(null, "Enter a guess between 1 and 100"); int userAnswer = Integer.parseInt(response); JOptionPane.showMessageDialog(null, determineGuess(userAnswer, computerNumber)); do { } while (userAnswer == computerNumber); } public static String determineGuess(int userAnswer, int computerNumber) { String message = null ; if(userAnswer <= 0 || userAnswer > 100) { message = "Invalid guess"; } else if (userAnswer == computerNumber) { message = "Correct"; } else if (userAnswer > computerNumber) { message = "too high" ; } else if (userAnswer < computerNumber) { message = "too low" ; } return message; } }
- Adjust the program so that it uses a loop to allow the user to repeat guessing untill they get the answer right. You can use a for loop, a while loop, or a do/while loop... it's your choice as long as it works. In this guessing game, the user should be prompt to type in a number as long as long as the user's answer doesn't match the number generated by the computer. This can be done in the main method.
- To adjust this program further, adjust and add lines to "count" the number of guesses that a user has taken. Create an integer variable called count to keep track of how many guesses a user has taken. Each time a user guesses, we will need to add 1 to the count variable. Display the number of guesses each time you tell the user whether their guess is correct, incorrect, or invalid. This should be added to the JOptionPane message box that is displayed in the main method.
- Instead of just testing for an incorrect number, you should determine if the guess is too high or low. If the user's guess is too low, you should display a message box that lets the user know that their guess is too low. If the user's guess is too high, you should display a message box that lets the user know that their guess is too high.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
