Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate random integer between 100 and 2000 in steps of 100 Java

Im currently trying to get a random integer between 100 and 2000 in steps of 100 like 300, 800, 1400 etc.

Thats what I found to get a random number between a range, but how do I manage to get a random number in steps of 100?

Random random = new Random();
int start = 100;
int end = 2000;
int result = random.nextInt(start - end) + start;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is whether you want 2000 included or not. And whether the step size reaches 2000 exactly. The calculation just needs to include the step size:

Random random = new Random();
final int start = 100;
final int end = 2000;
final int step = 100;
int result = start + step * random.nextInt((end - start)/step); // end excl.
int result = start + step * random.nextInt((end - start)/step + 1); // end incl.

As already commented, it is probably more clear to base all on a random number between 1 and 20, and scale that up.

int result = (1 + random.nextInt(20)) * 100; // 100 upto 2000 by 100.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading