参考下面程序实现猜大小的游戏,有两个按钮,分别表示用户猜大还是猜小。代码内部随机产生一个0-9的数,如果产生的数0-4为小,5-9为大。显示用户是否猜对。import java.awt.Color; import java.awt.event.; import javax.swing.; public class ButtonFrame extends JFrame{ private static final long serialVersionUID = 1L; private JPanel buttonPanel; private static final int DFFAULT_WIDTH=300; private static final int DFFAULT_HEIGHT=200; public ButtonFrame() { setSize(DFFAULT_WIDTH,DFFAULT_HEIGHT);
时间: 2024-02-15 14:04:53 浏览: 65
好的,这是一个Java的代码示例,实现了猜大小游戏。
```java
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
public class GuessGame extends JFrame {
private JPanel buttonPanel;
private JLabel resultLabel;
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
public GuessGame() {
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
setTitle("猜大小游戏");
buttonPanel = new JPanel();
JButton bigButton = new JButton("猜大");
bigButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
checkGuess("big");
}
});
buttonPanel.add(bigButton);
JButton smallButton = new JButton("猜小");
smallButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
checkGuess("small");
}
});
buttonPanel.add(smallButton);
resultLabel = new JLabel("猜大小游戏", JLabel.CENTER);
add(buttonPanel, "North");
add(resultLabel, "Center");
}
public void checkGuess(String guess) {
int randNum = (int) (Math.random() * 10);
if ((randNum < 5 && guess.equals("small")) || (randNum >= 5 && guess.equals("big"))) {
resultLabel.setText("恭喜你猜对了!");
resultLabel.setForeground(Color.GREEN);
} else {
resultLabel.setText("很遗憾,猜错了。");
resultLabel.setForeground(Color.RED);
}
}
public static void main(String[] args) {
GuessGame game = new GuessGame();
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setVisible(true);
}
}
```
这个程序创建了一个JFrame窗口,并添加了两个JButton和一个JLabel,点击猜大或猜小按钮时,程序会根据随机数判断是否猜对,并在JLabel上显示结果。注意,Java中需要使用equals方法比较字符串是否相等。
阅读全文