1 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超6個(gè)贊
在這種情況下,我更喜歡使用 Stream API。所以我認(rèn)為應(yīng)該是這樣:
public static void main(String[] args) {
System.out.print("Hvor mange rekker vil du spille?: ");
Scanner lesInn = new Scanner(System.in);
int nummer = lesInn.nextInt();
System.out.println("Lotto tallene er: ");
System.out.println();
for (int i = 0; i < nummer; i++) {
int[] lottoNummer = trekk();
System.out.print(lottoNummer[1] + " ");
System.out.print(lottoNummer[2] + " ");
System.out.print(lottoNummer[3] + " ");
System.out.print(lottoNummer[4] + " ");
System.out.print(lottoNummer[5] + " ");
System.out.print(lottoNummer[6] + " ");
System.out.print(lottoNummer[7] + " ");
System.out.print("Tilleggstall:(" + lottoNummer[7] + ")");
System.out.println();
}
}
public static int[] trekk() {
return new Random().ints(1, 35).distinct().limit(8).sorted().toArray();
}
創(chuàng)建一個(gè)隨機(jī)整數(shù)流,其中第一位數(shù)字表示最小值,最后一個(gè)數(shù)字表示最大值。Distinct 用于僅生成唯一的數(shù)字,Limit 用于限制數(shù)組的大小,Sorted 顯然用于排序。然后將其映射到數(shù)組并返回。
實(shí)際上,如果您不介意的話,我想重構(gòu)一下您的代碼,如下所示:
public static void main(String[] args) {
System.out.print("Hvor mange rekker vil du spille?: ");
Scanner lesInn = new Scanner(System.in);
int nummer = lesInn.nextInt();
System.out.println("Lotto tallene er: ");
System.out.println();
for (int i = 0; i < nummer; i++) {
int[] lottoNummer = trekk();
for (int num : lottoNummer) {
System.out.print(num + " ");
}
System.out.print("Tilleggstall:(" + lottoNummer[lottoNummer.length - 1] + ")");
System.out.println();
}
}
public static int[] trekk() {
return new Random().ints(1, 35).distinct().limit(8).sorted().toArray();
}
添加回答
舉報(bào)