In: Computer Science
In Java: Write a program that generates a random number and asks the user to guess the number and keeps track of how many guesses it took
Explanation:I have written the code in RandomGuess class and have used the JOPtionPane in the main method to accept and display the user input and output.I have also shown the output of the program, please find the images attached with the answer.Please upvote if you liked my answer and comment if you need any modification or explanation.
//code starts
import java.util.Random;
import javax.swing.JOptionPane;
public class RandomGuess
{
public static void main(String[] args)
{
Random random = new
Random();
int numberToGuess =
random.nextInt(100) + 1;
int guessCount = 0;
while (true)
{
try
{
guessCount++;
int x =
Integer.parseInt(JOptionPane.showInputDialog("Guess a number
between 1 and 100? "));
if (numberToGuess == x)
{
JOptionPane.showMessageDialog(null, "Your guessed it correct by
guessing " + guessCount + " times");
break;
}
if (x == 0 || x < 0)
{
JOptionPane.showMessageDialog(null, "you made " + guessCount + "
guesses");
break;
}
if (x < numberToGuess)
{
JOptionPane.showMessageDialog(null, "Your guess is too low, try
again");
continue;
} else if (x > numberToGuess)
{
JOptionPane.showMessageDialog(null, "Your guess is too high, try
again");
continue;
}
} catch
(NumberFormatException e)
{
JOptionPane.showMessageDialog(null, "Please
enter a valid integer");
continue;
}
}
}
}
Output: