3

How to draw a number from 0 to 4 in Java (Android)? How to use the Random function?

4 Answers 4

9

The follwing will do what you need.

Random r = new Random();
int randomInt = r.nextInt(5);

If you do this in a loop, make sure you initialize the Random outside of the loop.

Random r = new Random();
for(int i = 0;i < someThing; i++) {
    System.out.println(r.nextInt(5));
}

See the documentation for the Random class: http://download.oracle.com/javase/6/docs/api/java/util/Random.html

3

Please Pay Attantion - Calling each time the code:

Random r = new Random();

Will probably return you the same numbers (i guess few of you have noticed that phanamona).

I guess it connected somehow to the Java problem with random numbers: Java: Can (new Random()).nextInt(5) always return the same number? and: Java random always returns the same number when I set the seed?

Anyway my solution is to add a static variable to my class:

static Random sRandomGen = new Random();

and call the nextInt from the relevant method when i need the random number. Thatway i recieve an equal dividing between results.

int rnd = sRandomGen.nextInt(numofmatches - 1);

This solution works great for me.

2

One thing to be careful of is that you shouldn't create a new Random object every time you want a new number. This line should be executed once when the application starts:

Random r = new Random();

Then this should be called each time you want a new random number:

int x = r.nextInt(5);
2
System.out.println(""+(int) (Math.random()*5.0));

If you only need to generate a single random number, I believe it's slightly cheaper to use the Math.random() than to make an object.

Note: to generate any random integer from 0 to n, (0 inclusive, n exclusive), just use:

(int) (Math.random()*n);

To generate any random integer from m to m+n, (m inclusive, m+n exclusive), just use:

m + (int) (Math.random()*n);
2
  • Constructing an instance of Random is not necessary more expensive than your way
    – ognian
    Commented Dec 8, 2010 at 19:26
  • Ognian is correct, and to clarify, the first call to Math.random() actually creates a new java.util.Random object which will be used by all subsequent calls to Math.random().
    – robert_x44
    Commented Dec 8, 2010 at 20:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.