0

I know it is asked many times, but all of them are mixed with another questions that make it hard to understand. However I want to use Math.random to get a random number in 0-10.

In fact the random number will be used as index number of a list.

What I have done so far:

int random = Math.random(0,9); // Obviously does not work 
Alex Jj
  • 1,343
  • 10
  • 19
  • 30
  • 1
    It's not a BAD question... it's just been asked too many times... mainly because the API is confusing in that Math exposes a partial solution to generating random numbers which noobs (including myself at one time) find and therefore stop looking for a GOOD solution to this problem... so they ask an expert, again, and again, and again. Blame the highly-paid expert API designers, not the noob! – corlettk Aug 17 '13 at 01:08

3 Answers3

5

You can create a Random object and call nextInt to get an int between 0 and the inputted number (exclusive).

Random rnd = new Random();
int random = rnd.nextInt(11);  // returns range 0-10

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • 1
    Note: In practice there's no need to get a new instance of Random EVERY time you get a random value... and it can lead to "pointless excessive garbage". Just saying. – corlettk Aug 17 '13 at 00:36
  • 1
    Not just "no need", it's absolutely wrong to do so. If you recreate the object for every call, your numbers won't be random at all. – Lee Daniel Crocker Aug 17 '13 at 07:26
1

Don't use Math.random() Use Random#nextInt() instead:

int myInt=new Random().nextInt(11);

Or, as per comments, use

Random r=new Random();
int myInt=r.nextInt(11);

and reuse r as needed.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
1

To get a random item from any java.util.List (using generics) I get:

WARNING: The following code is NOT tested.

package forums;

import java.util.List;
import java.util.Random;

public final class ListHelper<T>
{
    private static final Random RANDOM = new Random();

    public T getRandom(List<T> list) {
        return list.get(RANDOM.nextInt(list.size()));
    }
}

... or you may prefer the non-generics solution, which can be static, but requires you to typecast the result of getRandom every time (everywhere) you call it

package forums;

import java.util.List;
import java.util.Random;

public final class Lists
{
    private static final Random RANDOM = new Random();

    public static Object getRandom(List list) {
        return list.get(RANDOM.nextInt(list.size()));
    }
}

Cheers. Keith.

corlettk
  • 13,288
  • 7
  • 38
  • 52