Program 4. Secret Number (50 points) Write a program to generate a random number
ID: 3678644 • Letter: P
Question
Program 4. Secret Number (50 points) Write a program to generate a random number between 1 - 100 and keep it as a secret number. The program will then check if a user can guess the secret number. The user can continue guessing the number until the number is found or the user can enter 0, which will terminate the program Each time the user makes a guess, the program will report as below: 1. Way Too High or Way Too Low (more than 30 off) 1. Way Too High or Way Too Low (more than 30 of) 2. High or Low (between 10 and 30 points off) 3. A Little High or A Little Low (less than 10 points off) If secret number is 74 and the user enters 26, the program will print "Way too Low". If the user then says 65, then the program will print "A Little Low". Write the program using JoptionPane. Name this program SecretNumber.java Note: The method showInputDialog in JOptionPane returns a string for the value entered by the user. To convert the string to an integer, use the wrapper class Integer. For example: with int I; String inputString; You can use = Integer.parseInt(inputString);Explanation / Answer
import javax.swing.*;
public class GuessingGame {
public static void main(String[] args) {
final int MAX = 100;
int secretNumber = (int)(Math.random() * MAX) + 1;
int guess;
int tries =0;
JOptionPane.showMessageDialog(null,"Pick a number between 1 and " + MAX +" Enter 0 to Quit");
while(true)
{
String input = JOptionPane.showInputDialog("Your guess ? ");
guess = Integer.parseInt(input);
tries += 1; // count the guess
if(guess == secretNumber){
JOptionPane.showMessageDialog(null,"You Win!! My secret number was " + secretNumber +" It took you "+tries + " guesses"); System.exit(0); break;
} else if(guess == 0) {
JOptionPane.showMessageDialog(null,"You Lose!! My secret number was " + secretNumber); System.exit(0); break;
}
if (guess < 0 || guess > MAX)
{JOptionPane.showMessageDialog(null,"Invalid guess ");
tries -= 1; // does not count as a guess
}
else if (guess > secretNumber + 30)
{JOptionPane.showMessageDialog(null," Way Too High! ");
}
else if (guess < secretNumber - 30)
{JOptionPane.showMessageDialog(null," Way Too Low! ");
}
else if (guess > secretNumber + 10 && guess < secretNumber + 30)
{JOptionPane.showMessageDialog(null," High! ");
}
else if (guess < secretNumber - 10 && guess > secretNumber - 30)
{JOptionPane.showMessageDialog(null," Low! ");
}
else if(guess < secretNumber + 10 && guess > secretNumber)
{JOptionPane.showMessageDialog(null," A Little High ! ");
}
else if(guess > secretNumber - 10 && guess < secretNumber)
{JOptionPane.showMessageDialog(null," A Little Low ! ");
}
}
} // end main
} // end class
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.