java - 如何从 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);
}
解决方案
您创建一个数组或 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);
推荐阅读
- ios - 我可以在真实(使用真实缓存)iTunes 环境中测试 InAppPurchase 吗?(不是沙箱)
- ruby-on-rails - Rails 4:Bundler 找不到 gem 的兼容版本
- java - 使用 KSTREAM 或 KSQL 的 JSON 数组到 JSON 对象
- c++ - 二进制文件处理程序未写入最后一个值
- java - 将日期数组转换为整数数组
- sql - 如何在postgresql中获得没有不必要区域的大小
- python - Python multiprocessing module freeze_support() line can obmitted error Windows
- tensorflow - 我可以在 Keras 中循环定义模型吗?
- angular - 无法通过 POSTMAN 访问 Angular 路由
- python - 双向 LSTM 模型尚未建立错误