Languages
[Edit]
EN

Java - generate random long, integer, double, float

9 points
Created by:
Root-ssh
68500

1. Generate random long

public static long nextLong() {
    return ThreadLocalRandom.current().nextLong();
}

Example:

System.out.println(nextLong()); // 387012672104004517
System.out.println(nextLong()); // 6852957493264943261
System.out.println(nextLong()); // -71063557433901021


2. Generate random long between min and max

public static long nextLongBetween(long min, long max) {
    return ThreadLocalRandom.current().nextLong(min, max);
}

Example:

System.out.println(nextLongBetween(10L, 1000L)); // 766
System.out.println(nextLongBetween(-100L, -5L)); // -87
System.out.println(nextLongBetween(387012L, 11176058387L)); // 4769035646


3. Generate random integer

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

Example:

System.out.println(nextInt()); // -852264371
System.out.println(nextInt()); // 191991333
System.out.println(nextInt()); // 32530510


4. Generate random integer between min and max

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

Example:

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


5. Generate random double

public static double nextDouble() {
    return ThreadLocalRandom.current().nextDouble();
}

Example:

System.out.println(nextDouble()); // 0.5428244431155195
System.out.println(nextDouble()); // 0.7784701343660209
System.out.println(nextDouble()); // 0.2506182623755011


6. Generate random double between min and max

public static double nextDoubleBetween(double min, double max) {
    return ThreadLocalRandom.current().nextDouble(min, max);
}

Example:

System.out.println(nextDoubleBetween(4.0d, 8.0d)); // 6.413976358616903
System.out.println(nextDoubleBetween(100.0f, 900.0f)); // 172.6124892961458
System.out.println(nextDoubleBetween(-6.0d, -3.0d)); // -3.3676577538936385


7. Generate random float

public static float nextFloat() {
    return ThreadLocalRandom.current().nextFloat();
}

Example:

System.out.println(nextFloat()); // 0.37941694
System.out.println(nextFloat()); // 0.8138674
System.out.println(nextFloat()); // 0.7531066


8. Generate random float between min and max

public static float nextFloatBetween(float min, float max) {
    return (ThreadLocalRandom.current().nextFloat() * (max - min)) + min;
}

Example:

System.out.println(nextFloatBetween(4.0f, 8.0f));     // 6.2839437
System.out.println(nextFloatBetween(100.0f, 900.0f)); // 115.800095
System.out.println(nextFloatBetween(-6.5f, -3.5f));   // -4.029911


Java - random numbers

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join