【发布时间】:2018-03-14 06:01:56
【问题描述】:
我有一个Object ArrayList,我需要使用Motor对象的toString()方法,它是Vehicle的一个参数> 对象。我的车辆对象位于一个 ArrayList 中,该 ArrayList 使用 for 循环进行迭代(我知道 foreach 循环会更容易,但这是任务的一部分)
这是循环的代码:
for (int i = 0; i < VehicleList.size(); i++) {
System.out.println();
String info = VehicleList.get(i).toString();
Motor m = VehicleList.get(i).motor;
String motorInfo = m.toString();
System.out.println(info);
System.out.println(m);
}
有一个错误提示“motor 无法解析或不是字段。
所有的类都应该允许这个工作,当然除非我遗漏了一个简单的错误。
这是电机类:
public class Motor {
protected String name;
protected int cylinders;
protected int bhp;
protected double displacement;
public Motor(String name, int cylinders, int bhp, double displacement) {
this.name = name;
this.cylinders = cylinders;
this.bhp = bhp;
this.displacement = displacement;
}
public String toString() {
return "Motor name= " + name + ", cylinders= " + cylinders + ", bhp=
" + bhp + ", displacement= " + displacement;
}
}
在此处初始化汽车和车辆(在 TestVehicle 类中):
//Motors
Motor EcoBoost = new Motor("EcoBoost", 6, 310, 2.3);
Motor Hemi = new Motor("Hemi", 8, 707, 5.7);
Motor P90D = new Motor("P90D", 0, 762, 0.0);
//Vehicles
Vehicle v0 = new PassCar("Ford", "Mustang", 2016, 44500.0, 5, true, EcoBoost);
Vehicle v1 = new PassCar("Tesla", "Model S", 2016, 121000.0, 2, true, P90D);
Vehicle v2= new Truck("Dodge", "Ram", 2016, 46000.0, "pickup", 1500, Hemi);
PassCar 和 Truck 是 Vehicle 的继承类,具有更多属性。如果需要,我可以发布 PassCar 或 Truck 类,但我认为这不是问题所在。我相信它来自 For-Loop,特别是 Motor m = VehicleList.get(i).motor; 行,但我不确定如何修复它.
车辆类别:
public class Vehicle {
protected String make;
protected String model;
protected int year;
protected double price;
public Vehicle(String make, String model, int year, double price) {
this.make = make;
this.model = model;
this.year = year;
this.price = price;
}
public void description() {
System.out.println("Description");
}
public String toString() {
return "make= " + make + ", model= " + model + ", year= " + year +
", price= " + price;
}
}
编辑:根据分配要求,不能有任何 Getter 或 Setter,它必须是 ArrayList,而不是常规 List。当我切换到我收到错误“类型不匹配:无法从 ArrayList 转换为 ArrayList
【问题讨论】:
-
Vehicle类是否有一个名为motor的字段? -
显示
VehicleList的声明。 -
请发帖
Vehicle班级。 -
在类
Vehicle中创建变量motor -
@Matthew 这是
Object的列表。将其更改为List<Vehicle>。
标签: java inheritance arraylist tostring