169k views
5 votes
Appendix D contains information about generating random numbers. To fully understand the process, you must learn more about Java classes and methods. For now, however, you can copy the following statement to generate and use a dialog box that displays a random number between 1 and 10: JOptionPane.showMessageDialog(null,"The number is "+ (1 + (int)(Math.random() * 10))); Write a Java application that displays two dialog boxes in sequence. The first asks you to think of a number between 1 and 10. The second displays a randomly generated number; the user can see whether his or her guess was accurate. (In future chapters, you will improve this game so that the user can enter a guess and the program can determine whether the user was correct. If you wish, you also can tell the user how far off the guess was, whether the guess was high or low, and provide a specific number of repeat attempts.) Save the file as RandomGuess.java

User Dean Sha
by
9.0k points

1 Answer

5 votes

Answer:

import javax.swing.JOptionPane;

public class RandomGuess {

public static void main(String[] args) {

String guessString = JOptionPane.showInputDialog(null, "Think of a number between 1 and 10");

int guess = Integer.parseInt(guessString);

int random = 1 + (int)(Math.random() * 10);

JOptionPane.showMessageDialog(null, "Your guess was " + guess + "\\The number was " + random + "\\" + (guess == random ? "You guessed it!" : "Better luck next time."));

}

}

Step-by-step explanation:

This program prompts the user to think of a number between 1 and 10, then generates a random number in the same range and displays it in a dialog box along with the user's guess. If the guess matches the random number, the program displays a "You guessed it!" message; otherwise, it displays a "Better luck next time" message.

User Shikjohari
by
7.5k points