Reputation: 43
I wanted to create a rock/paper/scissors game and add the function to implement a button which gives the user the option to replay the game without having to re-run the program, but when I press the "Do it again" button the random choice of the computer is always the same, how to do it that it picks a new random string from the array.
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;
}
});
Upvotes: 0
Views: 47
Reputation: 44398
It happens because you generate a random number once outside the on-click event. Move it to the method a few lines below:
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]);
}
});
Upvotes: 1
Reputation: 494
move int randomNumber=r.nextInt(arr.length);
into actionPerformed
Upvotes: 1