java
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GuessNumberGame extends JFrame {
private int answer;
public GuessNumberGame() {
answer = generateAnswer();
setTitle("四位数字猜数游戏");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField inputField = new JTextField(20);
JButton submitButton = new JButton("提交猜测");
JTextArea resultArea = new JTextArea(5, 20);
submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String input = inputField.getText();
String result = checkGuess(input);
resultArea.append(input + " - " + result + "\n");
if (result.equals("4A0B")) {
resultArea.append("恭喜您猜中了!\n");
}
inputField.setText("");
}
});
JPanel panel = new JPanel();
panel.add(new JLabel("请输入四位数字:"));
panel.add(inputField);
panel.add(submitButton);
add(panel, BorderLayout.NORTH);
add(resultArea, BorderLayout.CENTER);
setVisible(true);
}
private int generateAnswer() {
// 生成随机的四位数字
return (int) (Math.random() * 9000 + 1000);
}
private String checkGuess(String guess) {
int a = 0, b = 0;
for (int i = 0; i < 4; i++) {
if (guess.charAt(i) == String.valueOf(answer).charAt(i)) {
a++;
} else if (String.valueOf(answer).contains(String.valueOf(guess.charAt(i))) {
b++;
}
}
return a + "A" + b + "B";
}
public static void main(String[] args) {
new GuessNumberGame();
}
}
顶一下
(0)
0%
踩一下
(0)
0%
- 相关评论
- 我要评论
-
上一篇:返回栏目
下一篇:java生成纯数字id