我想创建一个石头/纸/剪刀游戏,并添加该功能以实现一个按钮,该按钮使用户可以选择重玩游戏而无需重新运行该程序,但是当我按“再次执行该操作“按钮,计算机的随机选择始终是相同的,如何从阵列中选择新的随机字符串。
JButton button1 = new JButton("The choice");
JButton button2 = new JButton("Do it again");
JTextField tekst1 = new JTextField(20);
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(tekst1);
c.add(button1);
c.add(button2);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (!hasBeenClicked) {
button1.addActionListener(new ActionListener() {
String[] arr={"rock", "paper", "scissors"};
Random r=new Random();
int randomNumber=r.nextInt(arr.length);
public void actionPerformed(ActionEvent evt) {
tekst1.setText(arr[randomNumber]);
}
});
} else {
tekst1.setText("");
}
hasBeenClicked = ! hasBeenClicked;
}
});
答案 0 :(得分:0)
将int randomNumber=r.nextInt(arr.length);
移至actionPerformed
答案 1 :(得分:0)
之所以发生,是因为您在点击事件之外生成了一个随机数。将其移至下面几行的方法中:
button1.addActionListener(new ActionListener() {
String[] arr={"rock", "paper", "scissors"};
Random r=new Random();
public void actionPerformed(ActionEvent evt) {
int randomNumber=r.nextInt(arr.length);
tekst1.setText(arr[randomNumber]);
}
});