I am trying to print a random number between 80 and 100. However when I print out this number I am getting numbers over 100?
Random num = new Random();
int percent = 80 + num.nextInt(100);
System.out.println(percent);
I am trying to print a random number between 80 and 100. However when I print out this number I am getting numbers over 100?
Random num = new Random();
int percent = 80 + num.nextInt(100);
System.out.println(percent);
Can you try something like this
There are two approach below
int resultNumber = ThreadLocalRandom.current().nextInt(80, 100 + 1);
System.out.println(resultNumber);
Random num = new Random();
int min =80;
int max=100;
System.out.println(num.nextInt(max-min) + min);
From the documentation of Random#nextInt(int):
Returns a pseudorandom, uniformly distributed int value between
0
(inclusive) and the specified value (exclusive), [...]
So your call
num.nextInt(100);
Generates numbers between 0
(inclusive) and 100
(exclusive). After that you add 80
to it. The resulting range for your percent
is thus 80
(inclusive) to 180
(exclusive).
In order to get a number from 80
to 100
, what you actually want to do is to generate a number from 0
to 20
and add that on top of 80
. So
int percent = 80 + num.nextInt(20);
The general formula is
int result = lowerBound + random.nextInt(upperBound - lowerBound);
Favor using ThreadLocalRandom
over new Random()
, it is faster because it sacrifices thread-safety (which you most likely do not need). So:
Random num = ThreadLocalRandom.current();
It actually also has an additional nextInt(int, int)
method for exactly this use case. See the documentation:
Returns a pseudorandom int value between the specified origin (inclusive) and the specified bound (exclusive).
The code would then just be:
int percent = ThreadLocalRandom.current().nextInt(80, 100);
All my examples so far assumed that 100
is exclusive. If you want it to be inclusive, just add 1
to it. So for example
int percent = ThreadLocalRandom.current().nextInt(80, 101);