How do I generate random integers within a specific range in Java?
@lebyy▲ 0 net votes
Problem: How do I generate a random int value in a specific range? The following methods have bugs related to integer overflow: randomNum = minimum + (int)(Math.random() * maximum); // Bug: randomNum can be bigger than maximum. Random rn = new Random(); int n =… Fix (from the top answer): Java 7+ In Java 1.7 or later , the standard way to do this (generate a basic non-cryptographically secure random integer in the range [min, max] ) is as follows: import java.util.concurrent.ThreadLocalRandom; // nextInt is normally exclusive of the top value, // so add 1 to make it See the relevant JavaDoc . This…