Java 如何从6个数字循环中提取前3个随机数?

Java 如何从6个数字循环中提取前3个随机数?,java,Java,所以我应该在Java中制作一个重载的程序。我已经制定了6个数字和前3个数字的平均值的2种方法。但我不知道如何将其存储到这两种方法的参数中。以下是我目前的代码: Random number = new Random(); Scanner input = new Scanner(System.in); int num; int sum = 0; for(int counter = 1; counter <=6; counter++){

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

    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);
    }
Random number=new Random();
扫描仪输入=新扫描仪(System.in);
int-num;
整数和=0;

对于(int counter=1;counter您创建一个数组或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]);
然后将函数的返回类型更改为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
}

我假定您不允许使用数组,所以只需将每个数组分配给一个变量即可

        num1 = 1 + number.nextInt(20);
        num2 = 1 + number.nextInt(20);
        num3 = 1 + number.nextInt(20);
        // and so on for six numbers.
然后

请注意,因为您没有使用双倍,所以您的平均值不会有小数点

否则,将数字放入数组中

您也可以这样做:

      public int avg(int[] array) {
            int sum = 0;
            for (int i = 0; i < array.length; i++) {
              sum += array[i];
            }
            return sum/array.length;
       }
public int avg(int[]数组){
整数和=0;
for(int i=0;i

如果允许,我建议将您的值从
int
更改为
double

尝试使用int数组
new int[6]
,并将随机数存储在那里。实现avg方法以处理数组,并作为第二个参数,从数组中选择多少值作为avg。在原始代码中,
返回((a+b+c+d+e+f)/6;
将6更改为6.0,并将
public static int
更改为
public static double
因此我按照您的建议做了(没有数组,因为我不应该使用它们:/)但在我这样做之后,我的平均值仍然是一个整数,但后面只有.00。这不是正确的平均值。你应该将所有
int
更改为
double
。int值始终是不带小数点的整数。只要将总和更改为double,返回类型就可以了。谢谢你的帮助。我将我下一次作业可能需要这个。我不能使用数组tho:/@ssethzz以这种方式创建6个单独的整数,并将返回类型更改为avg方法。我正在编辑答案
        num1 = 1 + number.nextInt(20);
        num2 = 1 + number.nextInt(20);
        num3 = 1 + number.nextInt(20);
        // and so on for six numbers.
       int avgerage = avg(num1, num2, num3, ...);
      public int avg(int[] array) {
            int sum = 0;
            for (int i = 0; i < array.length; i++) {
              sum += array[i];
            }
            return sum/array.length;
       }