写出随机0-9组成一个8位不重复数字的字符串,产生4个这样的字符串,也是互相不重复的
代码如下:
import java.util.Arrays;
import java.util.Random;
public class Ex1 {
public static void main(String[] args) {
//java写出随机0-9组成一个8位不重复数字的字符串,产生4个这样的字符串,也是互相不重复的
String[] as = new String[4];
ok:
for (int i = 0; i < 4; i++) {
String s = getStr();
for (String str : as) {
if (str != null && str.equals(s)) {
--i;
continue ok;
}
}
as[i] = s;
}
System.out.println(Arrays.toString(as));
}
static String getStr() {
Random rand = new Random();
Integer[] ns = new Integer[10];
for (int i = 0; i < 10; i++) ns[i] = i;
Arrays.sort(ns, (a, b) -> Math.random() > .5 ? 1 : -1);
StringBuilder sbu = new StringBuilder();
for (int i = 0; i < 8; i++) {
sbu.append(ns[i]);
}
return sbu.toString();
}
}
运行结果: