I have 3 classes : diet, dietTest and weeklyDiet
this is my code for diet :
public class Diet
{
private double weight;
private double calorie;
public double getW()
{
return weight;
}
public double getC()
{
return calorie;
}
public void setW(double w)
{
weight = w;
}
public void setC(double c)
{
calorie = c;
}
public Diet(double w, double c)
{
setW(w);
setC(c);
}
}
this is my code for weeklyDiet:
public class WeeklyDiet
{
private Diet [] onDiet;
public void retrieveDietRecord(Diet[] d)
{
Diet [] onDiet = d;
}
public double highestCalorieIntake()
{
double highest = onDiet[0].getC();
for(Diet calories : onDiet)
{
if(calories.getC() > highest)
{
highest = calories.getC();
}
}
return highest;
}
public double averageWeight()
{
double total = 0;
for(int i = 0 ; i < onDiet.length ; i )
{
total = onDiet[i].getW();
}
return total / 2;
}
}
this is my code for dietTest:
public class DietTest
{
public static void main(String [] args)
{
Diet d1 = new Diet(56.8, 1500);
Diet d2 = new Diet(59.1, 1850.5);
Diet [] myDiet = new Diet[2];
myDiet[0] = d1;
myDiet[1] = d2;
WeeklyDiet w = new WeeklyDiet();
w.retrieveDietRecord(myDiet);
w.averageWeight();
}
}
By running this code, seems like my Diet array in WeeklyDiet is not initialised, because the getAverage and findHighest methods cant use the data in array. I want to ask why when i execute w.averageWeight() method, the system show nullPointerException.
CodePudding user response:
You are initializing array, which exists only in retrieveDietRecord
public void retrieveDietRecord(Diet[] d)
{
Diet [] onDiet = d;
}
Diet [] onDiet = d;
This is not the instance variable onDiet
in WeeklyDiet
, but a local variable, whose scope is only inside the method. If you want to initialize the instance variable, you have to do it like this:
public void retrieveDietRecord(Diet[] d) {
this.onDiet = d;
}
Keyword this
is not mandatory in this exact case, but it's not a bad idea to be explicit.
CodePudding user response:
public void retrieveDietRecord(Diet[] d) {
this.onDiet = d;
}