java - 在 Java 中使用数组求最小值、最大值和平均值

标签 java arrays max average min

我们刚刚开始在编程入门类(class)中使用 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 - 在 Java 中使用数组求最小值、最大值和平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60531660/

相关文章:

java - 在服务器上部署java EE应用程序

c++ - 从具有两列的文件加载二维数组

sql - 如何选择 COUNT DISTINCT 为 MAX 的行?

php - 合并具有唯一属性的两行

java - 即使主签名正确,也会出现 "class does not have a static void main method accepting String[]"错误

java - 声音不会播放两次

java - 将 XML 转换为对象 xstream ( Android )

java - 在 Java 中,如何从组件类型的类中获取类的数组?

Java整数到字节数组

oracle - Oracles MAX函数的大O是什么?