So I am trying to generate a random number, but I can't use the Java random function because I need the numbers to be in the range of 1-25. What is the easiest aka most efficient way of doing this? If possible, an explanation would be great!
Asked
Active
Viewed 6,476 times
3 Answers
3
int random = (int)(Math.random() * 25 + 1);
or
int random = new Random.nextInt(24) + 1;
Bohemian
- 389,931
- 88
- 552
- 692
-
1I would use Random#nextInt instead. Floating point math scares me. – Thilo Sep 05 '13 at 23:28
1
I prefer to use the Java Random Class.
import java.util.Random;
And then generate the random nuber like this - assuming you want an integer:
Random gen = new Random();
int r = gen.nextInt(25) + 1;
finn
- 1,062
- 8
- 8