3

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
Lord_Peter
  • 53
  • 4

4 Answers4

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

Cristian
  • 198,401
  • 62
  • 356
  • 264
jjnguy
  • 136,852
  • 53
  • 295
  • 323
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.

Community
  • 1
  • 1
Ofershap
  • 687
  • 2
  • 7
  • 22
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);
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
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);
nnythm
  • 3,280
  • 4
  • 26
  • 36
  • Constructing an instance of Random is not necessary more expensive than your way – ognian Dec 08 '10 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 Dec 08 '10 at 20:02