可参考官方API:
https://docs.oracle.com/javase/7/docs/api/java/util/Random.html
@Test
public void test() {
Random random = new Random();// 创建新的随机数生成器
int nextInt = random.nextInt(101);// 生成随机数范围0-100;包含0但不包含101;
}
随机数有可能会出现重复,正好有个练习题练手顺便解决问题:
/**
* 题目:解决随机数重复问题且结果不能有0 1.定义数组来存储并判断下次存储随机数是否存在 2.不能确定循环几次才能满足结果,循环使用while
*/
@Test
public void test1() {
Random random = new Random();// 创建新的随机数生成器
int[] store = new int[5];// 定义数组存储每次生成的随机数
int index = 0;// 循环终止条件
while (index < 5) {
int nextInt = random.nextInt(6);
if (0 != nextInt && !contains(store, nextInt)) {
store[index++] = nextInt;// 如果条件成立则将当前随机数字存储到数组中,然后终止条件+1
}
}
ergodic(store);
}
/**
* 遍历数组判断参数二是否存在
*/
public boolean contains(int[] store, int nextInt) {
for (int i = 0; i < store.length; i++) {// 遍历数组
if (store[i] == nextInt) {
return true;
}
}
return false;
}
/**
* 遍历数组
*/
public void ergodic(int[] store) {
for (int i = 0; i < store.length; i++) {
System.out.println(store[i]);
}
}