Java :尝试使用可实例化的类和数组打印 3 周中每一周的平均温度



我需要一些帮助。我的任务是使用可实例化的类和数组开发一个应用程序,以存储 3 周(一周 7 天)的温度值,并计算和显示每周的平均值。我想我很接近,但我的代码返回 null 作为平均值,不确定出了什么问题!这是代码:

可实例化类:

public class Temperature {
    private double [][] tempData; //array to store temperature readings from 3 weeks
    private double [] avgOfWeek; // array to store avg of each week;
    public Temperature () {; // constructor to initialize instance variables with their default values, ie. tempData with null
    }
    // setter
    // setter method to assign / store a 2D array of double elements in the instance variable tempData
    public void setTemp (double [][] tempData) {
        this.tempData = tempData;
    }
    // processing
    public void calcAvg () {
        double [] avgOfWeek = new double [3];
        double [] sum = new double [3];
        int counter = 0;
            for (int row=0; row < tempData.length; row ++) {
                for (int col=0; col < tempData[row].length; col++) {
                    sum [row]= sum [row] + tempData [row][col];
                }
            avgOfWeek [row] = sum[row]/ tempData[row].length;
            }
    }
    // getter method to retrieve the average
        public double [] getAvg () {
            return avgOfWeek;
    }
}

应用:

public class TemperatureApp {
    public static void main (String [] args) {
        // declare a 2D array to store values of temperature 
        double [][] temp = new double [][] {
            {1,2,3,4,5,6,7},
            {7,6,5,4,3,2,1},
            {1,2,3,4,3,2,1},
        };

        Temperature myTemp = new Temperature ();
        myTemp.setTemp(temp);
        myTemp.calcAvg();
        double [] a = myTemp.getAvg();
        System.out.println (" The average temperature is " + a);
    }
}

您没有初始化正确的变量double [] avgOfWeek = new double [3]; . 删除代码double []

...
public void calcAvg () {
    avgOfWeek = new double [3];
    double [] sum = new double [3];
....

现在,您正在创建一个具有相同名称的新局部变量。每当在该方法中使用它时,它只引用该方法。

最新更新