Reputation: 85
I have an array of buttons with nine buttons. I am randomly generating two numbers for the buttons, how can I make it so that the randomly generated buttons can never equal themselves? I've already tried adding and subtracting one, but sometimes it crashes the game because 0 - 1 is void and so is 9 + 1
public void setButtons() {//finds a new random button
int rnd = new Random().nextInt(buttons.length);
int rnd2 = new Random().nextInt(buttons.length);
int newrnd = new Random().nextInt(buttons.length);
if(rnd != rnd2) {
buttons[rnd].getBackground().setColorFilter(Color.YELLOW, PorterDuff.Mode.MULTIPLY);
buttons[rnd2].getBackground().setColorFilter(Color.YELLOW, PorterDuff.Mode.MULTIPLY);
} else if(rnd == rnd2){
buttons[rnd].getBackground().setColorFilter(Color.YELLOW, PorterDuff.Mode.MULTIPLY);
buttons[newrnd].getBackground().setColorFilter(Color.YELLOW, PorterDuff.Mode.MULTIPLY);
}
}
Upvotes: 0
Views: 63
Reputation: 8490
Start with both ints equal to zero. Then while they are equal (which of course they will be initially), generate new random values for them. That loop will then continue until you get different values.
int rnd = 0;
int rnd2 = 0;
while (rnd == rnd2)
{
rnd = new Random().nextInt(buttons.length);
rnd2 = new Random().nextInt(buttons.length);
}
Upvotes: 1