用Java寫一個樂透抽獎程式共48個數字抽6個
以下是一個簡單的Java樂透抽獎程式,可以從1到48的數字中抽取6個不重複的數字:
import java.util.Random;
public class Lottery {
public static void main(String[] args) {
int[] numbers = new int[48];
for (int i = 0; i < 48; i++) {
numbers[i] = i + 1;
}
int[] result = new int[6];
Random rand = new Random();
for (int i = 0; i < 6; i++) {
int index = rand.nextInt(48 - i);
result[i] = numbers[index];
numbers[index] = numbers[47 - i];
}
System.out.print("樂透抽獎結果:");
for (int i = 0; i < 6; i++) {
System.out.print(result[i] + " ");
}
}
}
程式中使用了一個int陣列numbers來存儲所有可能的數字,然後使用Random類生成亂數來抽取6個不重複的數字,並存儲在另一個int陣列result中。最後,程式輸出抽獎結果。
原文地址: https://www.cveoy.top/t/topic/bMgM 著作权归作者所有。请勿转载和采集!