Java Non-Repeating Random Numbers Generator
In Java, you can use a Set to store randomly generated numbers and ensure that they are not repeated. The specific steps are as follows:
- Create a Set collection to store the generated random numbers.
- Generate random numbers using the Random class.
- Check if the generated random number already exists in the Set collection, if it does, generate a new one until a unique random number is produced.
- Add unique random numbers to a Set collection.
Here is an example code:
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class UniqueRandomNumberGenerator {
public static void main(String[] args) {
Set<Integer> set = new HashSet<>();
Random random = new Random();
while(set.size() < 10) {
int randomNumber = random.nextInt(100); // 生成0到99之间的随机数
if(!set.contains(randomNumber)) {
set.add(randomNumber);
}
}
System.out.println("随机生成的不重复数字:");
for(Integer num : set) {
System.out.println(num);
}
}
}
In the example above, we generated and printed 10 unique random numbers. The range and quantity of random numbers generated can be adjusted as needed.