0

I need some help please. My task is to develop an application using instantiable classes and arrays to store temperature values of 3 weeks (7 days in a week) and calculate and display average for each week. I think I am close, but my code returns null as value for average, not sure what is wrong! This is the code:

Instantiable class:

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;
    }
}

Application:

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);
    }
}
Sofo Gial
  • 697
  • 1
  • 9
  • 20
Msza
  • 13
  • 4
  • 2
    You have two `avgOfWeek` variables, remove the one declared in the `calcAvg` method . – Arnaud Jan 03 '19 at 15:11
  • 1
    the final print is not going to show what you expect. Check [here](https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) how to print an array – jhamon Jan 03 '19 at 15:15
  • thank you! thank really helped! – Msza Jan 03 '19 at 18:47

1 Answers1

4

You're not initializing the right variable double [] avgOfWeek = new double [3];. remove the code double [].

...
public void calcAvg () {

    avgOfWeek = new double [3];
    double [] sum = new double [3];
....

Right now you're creating a new local variable with the same name. Whenever you're using it in that method, it only references that one.

Neijwiert
  • 985
  • 6
  • 19