Languages
[Edit]
EN

Java - generate random int in range

7 points
Created by:
Kate_C
2860

1. ThreadLocalRandom.current().nextInt(min, max);

public static int nextInt(int min, int max) {
    return ThreadLocalRandom.current().nextInt(min, max);
}

Example:

System.out.println(nextInt(1, 100)); // 51
System.out.println(nextInt(1, 100)); // 98
System.out.println(nextInt(1, 100)); // 17
System.out.println(nextInt(500, 1000)); // 766
System.out.println(nextInt(-100, -5)); // -29

2. new Random().nextInt((max - min) + 1) + min;

public static int nextInt2(int min, int max) {
    return new Random().nextInt((max - min) + 1) + min;
}

Example:

System.out.println(nextInt2(1, 100)); // 60
System.out.println(nextInt2(1, 100)); // 24
System.out.println(nextInt2(1, 100)); // 70
System.out.println(nextInt2(500, 1000)); // 858
System.out.println(nextInt2(-100, -5)); //  -97

3. (int) (Math.random() * ((max - min) + 1)) + min;

public static int nextInt3(int min, int max) {
    return (int) (Math.random() * ((max - min) + 1)) + min;
}

Example:

System.out.println(nextInt3(1, 100)); // 32
System.out.println(nextInt3(1, 100)); // 26
System.out.println(nextInt3(1, 100)); // 99
System.out.println(nextInt3(500, 1000)); // 547
System.out.println(nextInt3(-100, -5)); // -88

4. new Random().ints(min, (max + 1)).limit(1).findFirst().getAsInt();

public static int nextInt4(int min, int max) {
    // java 8
    return new Random().ints(min, (max + 1)).limit(1).findFirst().getAsInt();
}

Example:

System.out.println(nextInt4(1, 100)); // 63
System.out.println(nextInt4(1, 100)); // 72
System.out.println(nextInt4(1, 100)); // 40
System.out.println(nextInt4(500, 1000)); // 893
System.out.println(nextInt4(-100, -5)); // -53

References:

ThreadLocalRandom.nextInt(int origin, int bound) - java docs
Random().nextInt(int bound) - java docs
Math.random() - java docs
Random().ints(int randomNumberOrigin, int randomNumberBound) - java docs

Java - random numbers

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.