class TestMy {
public static int num = 7;//決定生成不重複隨機數的個數
public static int value = 33;//生成隨機數的取值範圍
private static int index = 0;//狀態索引
public static void main(String[] args) {
int[] arr = new int[num];
boolean result = true;
while (result) {//控制是否繼續生成隨機數
Random rd = new Random();
int mm = rd.nextInt(value) + 1;
if (arr[arr.length - 1] == 0) {//決定是否繼續生成隨機數進行賦值
if (isHas(mm, arr, index)) {//判斷已生成隨機數是否與數組中已有數值重複
continue;
}
arr[index++] = mm;//將生成的不重複發的隨機數放入數組中
} else
result = false;
}
for (int j = 0; j < arr.length; j++) {
Arrays.sort(arr);
System.out.print(arr[j] + ",");
}
}
private static boolean isHas(int mm, int[] arr, int index) {
for (int i = 0; i < index; i++) {
if (mm == arr[i]) {
return true;
}
}
return false;
}
}