EN
Java - get random int
14
points
1. ThreadLocalRandom.current().nextInt();
public static int nextInt() {
return ThreadLocalRandom.current().nextInt();
}
Example:
System.out.println(nextInt()); // -852264371
System.out.println(nextInt()); // 191991333
System.out.println(nextInt()); // 32530510
System.out.println(nextInt()); // 1369144098
System.out.println(nextInt()); // 1764071021
2. new Random().nextInt();
public static int nextInt2() {
return new Random().nextInt();
}
Example:
System.out.println(nextInt2()); // 71226409
System.out.println(nextInt2()); // 2131479325
System.out.println(nextInt2()); // -1467723628
System.out.println(nextInt2()); // 1846156328
System.out.println(nextInt2()); // -1572933873
3. new Random().ints().limit(1).findFirst().getAsInt();
public static int nextInt3() {
// java 8
return new Random().ints().limit(1).findFirst().getAsInt();
}
Example:
System.out.println(nextInt3()); // -811935236
System.out.println(nextInt3()); // 1312834066
System.out.println(nextInt3()); // -1462402141
System.out.println(nextInt3()); // 2020063451
System.out.println(nextInt3()); // -966348427
If we want to generate random int in range then it is solved in below post: