Java Not greater than certain value

1.8k Views Asked by At

I just have a simple question. In Java, we know that the remainder of (y%x) can't be greater than x itself. Thus, we could hypothetically set all numbers less than a certain value of x, say 100. Yet what would be the opposite of this? What if we wanted to set all numbers above a certain value, say 20, to have a range [20,100]?

I was thinking that we could subtract 20 from both sides to have the range [0,80], and then take the modulus of 80, and then add 20 to it.

Am I right in believing this?

Thanks.

2

There are 2 best solutions below

1
On BEST ANSWER

The Random class includes nextInt(int) which (per the Javadoc) Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. So, 0-80 is

Random rand = new Random();
int v = rand.nextInt(81);

If you want it in the ragne 20-100 that would be

int v = rand.nextInt(81) + 20;
2
On

How can the remainder be greater that the divisor ? In other words you division is not complete.

If you want to of from 20-80 you can simple do

int i = 20 + randomInteger % 80;

This will be in the range of 20 -100.