user1730357
user1730357

Reputation: 355

Math.random range using the size of an arraylist

public void pickWinner() {
      int last = list.size() - 1;
      int number = (int)Math.random()*last;
      System.out.println("And the winner is...");
      Student winner = list.get(number);
      System.out.println(winner);
}

I am having problems generating a winner other than the first item in the ArrayList. I am thinking it is a problem with Math.random() because the size of my ArrayList seems to be correct, but it seems to only be generating 0's to get the first term in my ArrayList. What can I do to fix this problem?

Upvotes: 2

Views: 3320

Answers (2)

xmoex
xmoex

Reputation: 2702

Math.random() generates a number between 0.0 and 1.0. You are doing an integer conversion BEFORE you mulitply last, so the random number gets floored down to 0 and then the overall result will be always zero.

  int number = (int)(Math.random()*last);

should work correctly

Upvotes: 1

Sebastiaan van den Broek
Sebastiaan van den Broek

Reputation: 6351

Try this:

int number = (int)(Math.random()*last);

The problem is you're casting the math.random value to an int before multiplying it. The cast has a higher operator precedence (for a complete list, see http://introcs.cs.princeton.edu/java/11precedence/)

Additionally, your code will never pick the last Student in the list, you shouldn't -1 the 'last' int.

You could also consider using the Random class, i.e. new java.util.Random().nextInt(list.size()); so you don't have to worry about casts and how ints get rounded. You can even re-use the Random instance if you need to do it more than once.

Upvotes: 4

Related Questions