Java生成6位随机数

时间:2021-09-03 16:44:44
 
 

 

//新建一个HashSet

HashSet<String> sixHashSet = new HashSet<String>();

//满6位时结束循环

while (sixHashSet.size() != 6) {
  String temp = Integer.toString((int) (Math.random() * 10));
  sixHashSet.add(temp);
}

//拼接结果

String sixString = "";
for (String string : sixHashSet) {
  sixString = sixString + string;
}

//打印结果

System.out.println(sixString);

 

——————————————————————————————————————————————————————————————————————————————————————

 

以上实现方式容易出现数字相近或数字重复多,在网上看到一段代码,改良后发现效果比较理想。

 

//元素

int[] array = {0,1,2,3,4,5,6,7,8,9};

//随机对象
Random rand = new Random();

//循环产生
for (int i = 10; i > 1; i--) {
int index = rand.nextInt(i);
int tmp = array[index];
array[index] = array[i - 1];
array[i - 1] = tmp;
}

//拼接结果为字符串
int result = 0;
for(int i = 0; i < 6; i++)
result = result * 10 + array[i];
String sixString = Integer.toString(result);

//有可能出现5位数,前面加0补全
if (sixString.length() == 5) {
sixString = "0" + sixString;
}

//打印结果

System.out.println(sixString);