Search code examples
javamathinteger

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;

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.