1

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);
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
NightPixel
  • 27
  • 6

2 Answers2

1

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);
Dulaj Kulathunga
  • 1,248
  • 2
  • 9
  • 19
1

Explanation

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).


Solution

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);

Notes

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);
Zabuzard
  • 25,064
  • 8
  • 58
  • 82