Word To Word To - 4 months ago 18
Android Question

Randomly Switch Case

Hello friends I have 2 situation but I want to do it randomly. When user click button then there is 2 situation case0 or case1 randomly changes. So text's are randomly changes too...

*lastImageName and lastImageName2 are variable strings...

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;
}


But that's not working sometimes.. What's the rand. problem?

Answer

Remove the +1. Just do that: int newrand = rand.nextInt(2);