1 回答
TA贡献1828条经验 获得超6个赞
在这种情况下,我更喜欢使用 Stream API。所以我认为应该是这样:
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();
}
创建一个随机整数流,其中第一位数字表示最小值,最后一个数字表示最大值。Distinct 用于仅生成唯一的数字,Limit 用于限制数组的大小,Sorted 显然用于排序。然后将其映射到数组并返回。
实际上,如果您不介意的话,我想重构一下您的代码,如下所示:
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();
}
添加回答
举报