我刚刚开始学习 Java,我无法弄清楚我的方法 destroyEngine() 中做错了什么。如果你能帮助我,我将非常感激你。感谢您对我的代码的关注。我尝试更换 isReadyToDrive。创建了新变量brokenEngine。但看起来我没有称我的 int 距离正确。 我的主要。
public class CarManager {
public static void main(String[] args) {
Motorcycle suzuki = new Motorcycle("Suzuki GSX-R1000", 2021,16000, 600,
" black", "diesel", false, 0);
Motorcycle yamaha = new Motorcycle("Yamaha FZ1", 2007, 9000, 700, "orangE ",
"gas", false, 301000);
System.out.println(suzuki);
System.out.println(yamaha);
}
}
public class Motorcycle {
String name;
int yearOfProduction;
int price;
int weight;
Color color;
String engineType;
boolean isReadyToDrive;
int distance;
public Motorcycle(String name, int yearOfProduction, int price, int weight, Color color, String engineType,
boolean isReadyToDrive) {
this.name = name;
this.yearOfProduction = yearOfProduction;
this.price = price;
this.weight = weight;
this.color = color;
this.engineType = engineType;
this.isReadyToDrive = isReadyToDrive;
}
public Motorcycle(String name, int yearOfProduction, int price, int weight, String color, String engineType,
boolean isReadyToDrive, int distance) {
this.name = name;
this.yearOfProduction = yearOfProduction;
this.price = price;
this.weight = weight;
String colorTemp = color.toUpperCase();
this.color = Color.valueOf(colorTemp.replace(" ", ""));
this.engineType = engineType;
this.isReadyToDrive = destroyEngine();
this.distance = distance;
}
public boolean repair() {
isReadyToDrive = true;
return isReadyToDrive;
}
public boolean brokenEngine;
public boolean destroyEngine() {
if (distance >= 200000) {
brokenEngine = false;
} else {
brokenEngine = true;
}
return brokenEngine;
}
@Override
public String toString() {
return "Motorcycle [name=" + this.name + ", " + "yearOfProduction=" + yearOfProduction + ", " + "price="
+ this.price + ", " +
" weight=" + this.weight + ", " + "color=" + this.color + ", " + " engineType=" + this.engineType + ", "
+ "isReadyToDrive=" + this.isReadyToDrive
+ ", " + "distance=" + distance + "]";
}
}
在第二个构造函数中(您在
main
方法中实际使用的构造函数)
public Motorcycle(String name, int yearOfProduction, int price, int weight, String color, String engineType, boolean isReadyToDrive, int distance) {
// previous statements omitted
this.isReadyToDrive = destroyEngine();
this.distance = distance;
}
destroyEngine
方法使用实例变量distance
来决定是否返回true
或false
。但是,正如目前所写, distance
实例变量仍然具有默认值 0。
您必须在调用destroyEngine
之前给它一个值。
public Motorcycle(String name, int yearOfProduction, int price, int weight, String color, String engineType, boolean isReadyToDrive, int distance) {
// previous statements omitted
this.distance = distance;
this.isReadyToDrive = destroyEngine();
}