2016-08-06 14 views
1

こんにちは友人2つの状況がありますが、ランダムにしたいのですが。ユーザーがボタンをクリックすると、2つの状況case0またはcase1がランダムに変更されます。だから、テキストのは、ランダムにランダムに切り替える場合

Random rand = new Random(); 
int newrand = rand.nextInt(1) + 1; 

switch(newrand) { 
case 0: 
    text1.setText(lastImageName); 
    text2.setText(lastImageName2); 
    break; 
case 1: 
    text1.setText(lastImageName2); 
    text2.setText(lastImageName); 
    break; 
} 

しかし、それは...ランドは何時々働いていない...あまりにも...

* lastImageNameとlastImageName2が可変の文字列で変更されています。問題?

答えて

0

+1を削除します。ちょうどそれを行う:int newrand = rand.nextInt(2);

0

Random#nextInt(int)は、0とそれ以上の排他的な排他的論理和を生成します。つまり、nextInt(1)は常に0を返します。代わりに、あなただけ使用する必要があります。

int newrand = rand.nextInt(2); 
1
Random rand = new Random(); 
int a = 0; 
int b = 1; 
int c = random.nextBoolean() ? a : b; 
0

あなただけ、あなたはまた、

Random rand = new Random(); 
int newrand = rand.nextInt() % count;//count = 2 for your case 

switch(newrand) { 
case 0: 
    text1.setText(lastImageName); 
    text2.setText(lastImageName2); 
    break; 
case 1: 
    text1.setText(lastImageName2); 
    text2.setText(lastImageName); 
    break; 
} 
を使用することができ、複数の場合は

boolean state = rand.nextBoolean(); 
text1.setText(state?lastImageName:lastImageName2); 
text2.setText(state?lastImageName2:lastImageName); 

を使用する2つのケースを持っている場合

関連する問題