【发布时间】:2020-06-17 06:37:54
【问题描述】:
在我们的编程课程介绍中,我们才刚刚开始使用 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
}
}
【问题讨论】:
-
您的问题是什么?有什么不工作吗?
-
我看到的第一个问题是您没有将输入值写入数组。你可以使用
testScore = in.nextInt();,但这个testScore再也不会被使用了。将此值分配给您的数组,例如listOfScores[index] = testScore或直接使用listOfScores[index] = in.nextInt()。 -
对于初学者,您应该将捕获的每个条目存储在数组中 - 而不是 testScore。还有像 Integer.MIN_VALUE/Integer.MAX_VALUE 之类的东西,您应该使用它来播种最大/最小值占位符,以便在每次迭代时进行比较。
-
@JGFMK 我认为最好的方法是用
listOfScores[0]的值初始化 min 和 max 这样,你的数字范围无关紧要。 -
这也可以在一个循环中完成
标签: java arrays max average min