我有一个计算特定成员所覆盖的总距离的方法,它返回一个双数组,如下所示:
public double[] getTotalDistances(){
double[] distance;
distance = new double[3];
for(Activity r: diary ){
if(r instanceof Run){
distance[0] += r.getDistance();
}
}
for(Activity c: diary ){
if(c instanceof Cycle){
distance[1] += c.getDistance();
}
}
for(Activity s: diary ){
if(s instanceof Swim){
distance[2] += s.getDistance();
}
}
return distance;
}
现在对象(成员)存储在另一个名为members的数组中,如下所示:
public boolean addMember(Member m){
boolean result = false;
for(int i = 0; i < members.length; i++){
if(members[i] == null){
members[i] = m;
result = true;
break;
}
}
return result; //this is returned to have an indication if the member was added successfully or not
}
现在我需要一种方法来打印成员的所有总距离,我试过这个:
public void displayDistances() {
for(int i = 0; i < members[i].getTotalDistances().length; i++){
System.out.println(members[i].getTotalDistances()[i]);
}
}
但是,这只会打印第一个成员的第一个元素,然后是0,并在其上面给出一个空指针异常。任何帮助都会非常感激!
答案 0 :(得分:1)
这里有几件事。首先,我重构了你的getTotalDistances()方法。
public double[] getTotalDistances(){
double[] distance = new double[3];
for(Activity activity: diary) {
if (activity instanceof Run) {
distance[0] += activity.getDistance();
} else if (activity instanceof Cycle) {
distance[1] += activity.getDistance();
} else {
distance[2] += activity.getDistance();
}
}
return distance;
}
然后你的displayDistances()应改为:
public void displayDistances(){
for(int i = 0; i < members.length; i++){
double total = 0;
double[] distances = members[i].getTotalDistances();
for(int j = 0; j < ditances.length; j++){
total += distances[j];
}
System.out.println(total);
}
}
这将打印每个成员的总行进距离。祝你好运!