- 使用Math類的random()方法生成0到1之間的隨機數:
double randomNum = Math.random();
- 使用Random類的nextInt()方法生成指定范圍內的隨機整數:
Random random = new Random();
int randomInt = random.nextInt(100);
- 使用ThreadLocalRandom類的nextInt()方法生成指定范圍內的隨機整數:
int randomInt = ThreadLocalRandom.current().nextInt(0, 100);
- 使用SecureRandom類的nextInt()方法生成安全的隨機整數:
SecureRandom random = new SecureRandom();
int randomInt = random.nextInt(100);
- 使用Apache Commons Math庫中的RandomDataGenerator類生成指定范圍內的隨機數:
RandomDataGenerator randomDataGenerator = new RandomDataGenerator();
int randomInt = randomDataGenerator.nextInt(0, 100);