0
Using random in Java 0 to 100
I'm learning about how to use the Random class I'm new, and I'm a little confused, because I want to generate a Random number from 0 to 100. I did it with these two sentences: Random rnd = new Random(); System.out.println((int)(rnd.nextDouble() * 100 + 1)); System.out.println(Math.abs(rnd.nextInt()) % (100 + 1)); Both sentence create a random number from 0 to 100, but which one is better? Is there another way to generate a random number from 0 to 100? How can I generate a random number from 50 to 100?
2 Answers
+ 3
There's many ways. I have no idea which is the best, there likely very similar performance wise. Although, Math.random() may be nice since you don't need to create an instance of a class plus no imports required. LocalRandom seemed to be recommended nowadays.
I'd recommend not using your abs() way, try to minimize the operations.
Examples using some methods, from 50-100.
int randNum = (int)((Math.random() * (50 + 1)) + 50);
OR
From java.util
Random rnd = new Random();
int randNum = rnd.nextInt((100-50)+1) + 50
OR
From java.util.concurrent
int randNum = ThreadLocalRandom.current().nextInt(50, 100 + 1);
*I wrote +1 sometimes to show the number is exclusive, and showed all work.*
+ 1
Use this Code:
Random rndNumber= new Random();
int a = rndNumber.nextInt(100);