Java
创建一个长度为6的数组,要求随机取值为1-30,同时元素值各不相同
方法一:创建标志flag
public class Test{
public static void main{
int[] arr6 = new int[6];
for (int i = 0; i < arr6.length; i++) {
arr6[i] = (int)(Math.random()*30) +1;
boolean flag = false;
while (true) {
for (int j = 0; j < i; j++) {
if (arr6[j] == arr6[i]) {
flag = true;
break;
}
}
if (flag) {
arr6[i] = (int)(Math.random()*30)+1;
flag = false;
continue;
}
break;
}
}
for (int i: arr6) {
System.out.print(i+"\t");
}
}
}
方式二:自减
public class Test{
public static void main{
int[] arr7 = new int[7];
for (int i = 0; i < arr7.length; i++) {
arr7[i] = (int) (Math.random() * 30) + 1;
for (int j = 0; j < i; j++) {
if (arr7[i] == arr7[j]) {
i--;
break;
}
}
}
for (int i : arr7) {
System.out.print(i+" ");
}
}
}