第一种方式:使用Random()方法生成一个随机数然后追加到数组里
方便后续使用封装成方法
public static ArrayList getRandom() {
Random random = new Random();
ArrayList list = new ArrayList();
//每次随机生成一个数字,循环5次(下标从0开始)得到6个随机数,保存到数组里
for(int i = 0; i <= 5; i++) {
//只需要0-9之间的随机6位,所以nextInt(9)里就生成到9就好了,包含0在里面
list.add(random.nextInt(9));
}
return list;
}
调用方法查看结果:
[1, 2, 4, 2, 6, 1]
[3, 1, 8, 3, 2, 1]
[2, 7, 2, 0, 7, 2]
多试几次每次得到的都是不一样的6位数字
第二种方式:与第一种方式相似,但是以字符串的形式返回
为了方便后续使用也封装成方法
public static String getStringRandom() {
Random random = new Random();
//把随机生成的数字转成字符串
String str = String.valueOf(random.nextInt(9));
for (int i = 0; i < 5; i++) {
str += random.nextInt(9);
}
return str;
}
最终效果如下:
602835
211714
486422