Android - Int不能等于另一个int

时间:2014-02-09 04:22:12

标签: android random

我有一组带有九个按钮的按钮。我随机为按钮生成两个数字,我怎样才能使随机生成的按钮永远不等于自己呢?我已经尝试过添加和减去一个,但有时它会导致游戏崩溃,因为0 - 1是无效的,因此是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);
    }
}

1 个答案:

答案 0 :(得分:1)

从两个整数开始等于零。然后,当它们相等时(当然它们最初会是这些),为它们生成新的随机值。然后该循环将继续,直到您获得不同的值。

int rnd = 0;
int rnd2 = 0;

while (rnd == rnd2)
{
    rnd = new Random().nextInt(buttons.length);
    rnd2 = new Random().nextInt(buttons.length);
}