Question: In this lab, you will make additions to a Java program provided. The program is a guessing game. A random number between 1 and 1

In this lab, you will make additions to a Java program provided. The program is a guessing game. A random number between 1 and 10 is generated in the program. The user enters a number between 1 and 10, trying to guess the correct number. If the user guesses correctly, the program congratulates the user and then the loop that controls guessing numbers exits; otherwise, the program asks the user if they want to guess again. If the user enters Y, they can guess again. If the user enters N, the loop exits. You can see that the "Y" or "N" is the sentinel value that controls the loop. Note that the entire program has been written for you. You need to add code that validates correct input, which is "Y" or "N" when the user is asked if they want to guess a number, and a number in the range of 1 through 10 when the user is asked to guess a number.
import javax.swing.JOptionPane;
public class GuessNumber
{
public static void main(String args[])
{
int number; // Number to be guessed.
int userNumber; // User's guess.
String stringNumber; // String version of user's guess.
String keepGoing; // Contains a "Y" or "N" determining if the user wants to continue.
number =1+(int)(Math.random()*10); // Generate random number.
// Prime the loop.
keepGoing = JOptionPane.showInputDialog("Do you want to guess a number? Enter Y or N");
// Validate input.
// Enter loop if they want to play.
while(keepGoing.compareTo("Y")==0)
{
// Get user's guess.
stringNumber = JOptionPane.showInputDialog("I'm thinking of a number. .
Try to guess by entering a number between 1 and 10");
userNumber = Integer.parseInt(stringNumber);
// Validate input.
// Test to see if the user guessed correctly.
if(userNumber == number)
{
keepGoing ="N";
System.out.println("You are a genius. That's correct!");
}
else
{
keepGoing = JOptionPane.showInputDialog("That's not correct. Do you want to guess again? Enter Y or N");
// Validate input.
}
}// End of while loop.
}
}// End of GuessNumber class.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!