java猜数字游戏窗口
时间: 2023-11-25 22:51:48 浏览: 86
java 猜数字游戏
以下是一个简单的Java猜数字游戏窗口的实现:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GuessNumberGame extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private int num = -1;
private int count = 0;
private JLabel label1, label2;
private JTextField textField;
private JButton button;
public GuessNumberGame() {
super("Guess Number Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);
setLocationRelativeTo(null);
label1 = new JLabel("Guess a number between 0 and 100:");
label2 = new JLabel("");
textField = new JTextField(10);
button = new JButton("Guess");
button.addActionListener(this);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 1));
panel.add(label1);
panel.add(textField);
panel.add(button);
panel.add(label2);
setContentPane(panel);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (num == -1) {
num = (int) (Math.random() * 100);
}
try {
int guess = Integer.parseInt(textField.getText());
count++;
if (guess == num) {
label2.setText("Congratulations! You guessed the number in " + count + " tries.");
button.setEnabled(false);
} else if (guess < num) {
label2.setText("Too low. Try again.");
} else {
label2.setText("Too high. Try again.");
}
} catch (NumberFormatException ex) {
label2.setText("Invalid input. Please enter an integer between 0 and 100.");
}
}
}
```
这个程序实现了一个简单的猜数字游戏窗口,用户需要在文本框中输入一个0到100之间的整数,然后点击“Guess”按钮进行猜测。程序会根据用户的猜测给出相应的提示,直到用户猜中为止。
阅读全文