2014-02-09 14 views
0

我有一个按钮阵列与九个按钮。我随机生成两个按钮的数字,我怎么能使它随机生成的按钮永远不会自己平等?我已经尝试过加减之一,但有时它崩溃的比赛,因为0 - 1是无效的,所以是9 + 1Android - 诠释不能等于另一个int

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); 
    } 
} 
+0

添加一个可以工作,但是当它通过结束(9)并将其换回到零时,您必须记住要换行。或者,你可以循环选择第二组新的随机数,并做到这一点,直到你得到一对不相等的对。 – Chris

回答

1

开始与两个整数等于零。然后,当他们是平等的(当然他们将是最初),为他们产生新的随机值。该循环将继续,直到你得到不同的值。

int rnd = 0; 
int rnd2 = 0; 

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

沿着这些线我会建议以及 – Mayhem