user3053246
user3053246

Reputation: 753

How to randomly choose between two choices

Let's say I have to choices and a button that randomly picks one of those choises:

How do I randomly pick the answer using the button?

Upvotes: 0

Views: 2192

Answers (2)

Ryan Sayles
Ryan Sayles

Reputation: 3441

If you are using the same type, in this case strings you can do something like:

List<String> list = new ArrayList<String>();
list.add(string1);
list.add(string2);
ect..
list.shuffle();
list.get(0);

This will put all the string values into an ArrayList, shuffle the list, and then return the first element which will be random and different each time you call .shuffle()

Upvotes: 0

Jilberta
Jilberta

Reputation: 2866

You can do something like this in your button's onClick() method:

Random rand=new Random() 
int x = rand.nextInt(2);
if(x == 0)
  //  choose answer 1
else
//   choose answer 2

You can use Math library too:

int x = (Math.random() < 0.5) ? 0:1;
if(x == 0)
  //  choose answer 1
else
//   choose answer 2

Upvotes: 4

Related Questions