隨機生成7個不重複的彩票號碼 (33選7)

 

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;
 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章