import javax.swing.*; public class GuessNumber { public GuessNumber() { // Reading difficulty level String difficultyStr = JOptionPane.showInputDialog(null, "Enter a difficulty level"); int difficulty = Integer.parseInt(difficultyStr); // Generate the random value int correctValue = (int)(Math.random() * difficulty) + 1; // Loop asking user for values String guessStr; String enterValueStr = "Enter a value between 1 and " + difficulty + " (0 to quit)"; int guess, attempts = 0; do { guessStr = JOptionPane.showInputDialog(null, enterValueStr); guess = Integer.parseInt(guessStr); if (guess != 0) { if (guess != correctValue) { JOptionPane.showMessageDialog(null, "Incorrect guess", "", JOptionPane.INFORMATION_MESSAGE); } attempts++; } } while ((guess != correctValue) && (guess != 0)); // Report attempts and correct value String finalMessage; if (guess == correctValue) { finalMessage = "You guessed the value! (" + correctValue + ")"; } else { finalMessage = "You did not guess the value (" + correctValue + ")"; } finalMessage += "\nNumber of Attempts: " + attempts; JOptionPane.showMessageDialog(null, finalMessage, "Final Report", JOptionPane.INFORMATION_MESSAGE); } public static void main(String[] args) { new GuessNumber(); System.exit(0); } }