Write a Java program that plays \"guess the number\". The program will generate
ID: 3549432 • Letter: W
Question
Write a Java program that plays "guess the number".
The program will generate a random number from 1 through 10.
The user enters a number in the textfield and clicks the "Check
Answer" button.
The computer will tell the user if the guess is too high or too low.
If the guess is too high or too low, the user will guess another number
and click the "Check Answer" button.
The user will guess numbers until the message "You guessed the
number!" is displayed.
Set the frame size to 300, 125
Output should look like this: http://imgur.com/R05k9Gl
I started it up, but my month off for winter break has really taken its toll on what I can remember, and I can't get it right.
Explanation / Answer
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GuessingGame extends JFrame
{
private JTextField txtNumber = new JTextField(5);
private JButton btnCheck = new JButton("Check Answer");
private JLabel lblHint = new JLabel("Please enter your guess.");
private int number;
// constructor the GUI
public GuessingGame()
{
setTitle("Guessing Game");
setLayout(new FlowLayout());
add(new JLabel("I have a number between 1 and 10."));
add(lblHint);
add(txtNumber);
add(btnCheck);
// generate the number
number = (int)(Math.random() * 10) + 1;
// add button handler
btnCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
checkAnswer();
}
});
}
// check the answer
public void checkAnswer()
{
try
{
int val = Integer.parseInt(txtNumber.getText());
String result = "";
if (val < number)
result = "Too Low. Try a higher number.";
else if (val > number)
result = "Too High. Try a lower number.";
else
result = "You guessed the number!";
lblHint.setText(result);
}
catch (Exception e)
{
}
}
// The main method create the GuessGame
public static void main(String[] args)
{
GuessingGame game = new GuessingGame();
game.setSize(300, 125);
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setVisible(true);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.