java - 在 Java 中使用数组查找最小值、最大值和平均值
问题描述
在我们的编程课程介绍中,我们刚刚开始用 Java 编写代码,我对这个特定任务的错误之处感到很困惑。目标是创建一个程序,输入存储在数组中的 15 个测试分数(值介于 1 到 100 之间)。然后使用该数组计算最小、最大和平均分数的输出(平均值必须是累加器)。
不允许使用带有 break 语句的无限循环。下面是我开始的代码以及教授的符号。
我们在 Codiva 中运行此代码,当我运行它时,没有任何内容。不知道我错过了什么。
import java.util.Scanner;
class TestScoresCalulcated {
public static void main(String[] args) {
/**Declarations**/
int index = 0;
int index2 = 0;
int min;
int max;
int testScore;
int NUM_SCORES = 15;
int[] listOfScores = new int[NUM_SCORES];
Scanner in = new Scanner(System.in);
for (index = 1; index <= NUM_SCORES; index++) {
/**TODO:create a loop and make the variable index the loop control variable**/
System.out.println("Enter in an integer:");
testScore = in .nextInt();
}
min = 1;
max = 100;
for (index2 = 1; index2 <= NUM_SCORES; index2++) {
if (max < listOfScores[index2]) {
max = listOfScores[index2];
}
System.out.println("Doing Max Calculation: " + max);
}
for (index2 = 1; index2 <= NUM_SCORES; index2++) {
if (min > listOfScores[index2]) {
min = listOfScores[index2];
}
System.out.println("Doing Min Calculation: " + min);
}
//use the index2 as a loop variable as a index for the array.
/*TODO:create another loop
//TODO:check if the element in the array less than max
System.out.println("Doing max calulcation");
//TODO: assign max variable
//TODO:check if the element in the array less than min
System.out.println("Doing min calculation");
//consider doing accumulator calculation here to get the average.
**/ //end of loop2
//output the results here
}
}
解决方案
您正在使用值 0 初始化索引,然后用 1 覆盖它,因此您正在从第二个值开始访问您的数组。此外,您的循环使用数组的长度作为索引 (15) 结束,这实际上是数组中不存在的第 16 个元素,您肯定会在那里遇到错误。
您需要使用 < 而不是 <=
还有@Nils 所说的首先不保存数组中的值。
推荐阅读
- java - 在同一对象上执行不同方法时使 2 个线程交替
- sql-server - 在 SQL 中使用主表中始终更新的数据创建副本表的最佳方法
- javascript - bson 的 ObjectId 是否有 tryParse 函数?
- java - 使枚举不区分大小写
- javascript - 开发人员中的 Acumatica API 登录限制
- c# - 如何在 DbContext EF 多线程中开始第二个操作之前等到完成第一个操作
- python - 用 BS 解析不一致的多级 XML
- azure - 使用 Graph API 从 Azure AD 获取正确的电话属性
- keycloak - 在 Keycloak 预览模式下按组进行用户管理
- python - 使用 Python 将序列值放入矩阵中