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 7,195 times
3 Answers
3
int random = (int)(Math.random() * 25 + 1);
or
int random = new Random.nextInt(24) + 1;

Bohemian
- 412,405
- 93
- 575
- 722
-
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,155
- 8
- 9