abstract class Express{ public int weight; public abstract int getWeight(); public abstract int getTotal(); } public class SLExpress extends Express{ public int cost; public SLExpress(){ } public SLExpress(int weight){ super.weight=weight; } public int getTotal(int weight){ cost=12+(weight-1)*2; return cost; } } public class DDExpress extends Express{ public int cost; public DDExpress(){ } public DDExpress(int weight){ super.weight=weight; } public int getTotal(int weight){ cost=5+weight-1; return cost; } } public class CaicaiStation{ public int sum; public int calculate(Express[] ex){ for(int i=0;i<ex.length;i++){ sum+=ex[i]; } } }纠错
时间: 2024-03-09 07:49:55 浏览: 137
在这段代码中,`CaicaiStation`类中的`calculate()`方法中有一个错误:
1. 在`sum+=ex[i];`语句中,`ex[i]`是`Express`类型的对象,不能直接进行加法操作,需要调用`ex[i].getTotal()`方法来获取该快递的总费用。
下面是修改后的代码:
```
abstract class Express {
public int weight;
public abstract int getWeight();
public abstract int getTotal();
}
public class SLExpress extends Express {
public int cost;
public SLExpress() {
}
public SLExpress(int weight) {
super.weight = weight;
}
public int getWeight() {
return weight;
}
public int getTotal() {
cost = 12 + (weight - 1) * 2;
return cost;
}
}
public class DDExpress extends Express {
public int cost;
public DDExpress() {
}
public DDExpress(int weight) {
super.weight = weight;
}
public int getWeight() {
return weight;
}
public int getTotal() {
cost = 5 + weight - 1;
return cost;
}
}
public class CaicaiStation {
public int sum;
public int calculate(Express[] ex) {
for (int i = 0; i < ex.length; i++) {
sum += ex[i].getTotal();
}
return sum;
}
}
```
阅读全文