java - 如何从 6 个数字循环中取出前 3 个随机数?

标签 java

所以我应该用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);
    }

最佳答案

创建一个 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);

关于java - 如何从 6 个数字循环中取出前 3 个随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60643062/

相关文章:

具有水平滚动功能的 JavaFX 8 Tableview

java - 无法编译 WordCount.java

java - 线程 "main"java.lang.StackOverflowError actionListeners 中出现异常

java - 从哪里可以获得 Eclipse 的 derby 核心插件?

java - Ormlite:如何按数据类型 = 字符串的日期排序? sort 在哪里会将其视为日期而不是字符串?

java - 用于 4 眼检查的 hibernate 锁定对象

java - 什么是原始类型,为什么我们不应该使用它呢?

java - 使用@EmbeddedId和@MapsId会导致插入NULL(违反NOT NULL约束)

java - Android Context.bindService 总是返回 false 并且永远不会触发 ServiceConnection 对象

java - BCryptPasswordEncoder Spring Security 未定义