首页 > 解决方案 > 如何从 6 个数字循环中获取前 3 个随机数?

问题描述

所以我应该用Java制作一个重载程序。我已经制定了 2 种方法来平均 6 个数字和前 3 个数字。但我不知道如何将它存储到这两种方法的参数中。到目前为止,这是我的代码:

    Random number = new Random();
    Scanner input = new Scanner(System.in);

    int num;
    int sum = 0;

    for(int counter = 1; counter <=6; counter++){
        num = 1 + number.nextInt(20);
        System.out.printf("Random number #%s: %s%n",counter,num);
        }

    }
    public static int avg (int a, int b, int c, int d, int e, int f){
        return ((a+b+c+d+e+f)/6);
    }
    public static int avg (int a, int b, int c){
        return((a+b+c)/3);
    }

标签: java

解决方案


您创建一个数组或 int 列表并将随机数存储到数组/列表中。然后,您可以使用数组/列表的元素调用这两个方法

int[] array = new int[6];
for(int counter = 1; counter <=6; counter++){
    num = 1 + number.nextInt(20);
    array[counter-1] = num;
    System.out.printf("Random number #%s: %s%n",counter,num);
    }
}

int avg1 = avg(array[0],array[1],array[2]);
int avg2 = avg(array[0],array[1],array[2],array[3],array[4],array[5]);

不使用数组,您创建 6 个 int 并删除 for 循环

int i1 = 1 + number.nextInt(20);
int i2 = 1 + number.nextInt(20);
int i3 = 1 + number.nextInt(20);
int i4 = 1 + number.nextInt(20);
int i5 = 1 + number.nextInt(20);
int i6 = 1 + number.nextInt(20);

然后将函数的返回类型更改为 double

public static double avg (int a, int b, int c, int d, int e, int f){
     return ((a+b+c+d+e+f)/6.0); //change 6 to 6.0 so it doesn't do integer divide
}
public static double avg (int a, int b, int c){
     return((a+b+c)/3.0); //change 3 to 3.0 for same reason as above
}
double avg1 = avg(i1,i2,i3);
double avg2 = avg(i1,i2,i3,i4,i5,i6);

推荐阅读