【发布时间】:2021-08-02 05:59:11
【问题描述】:
朋友们好,我正在尝试为一个项目构建一个 Car 类。以下代码中有许多方法以及我无法构建的 if 语句,请考虑以下代码
public class Car extends Vehicle {
private boolean isDriving;
private final int horsepower;
private boolean needsMaintenance = false;
private int tripsSinceMaintenance = 0;
Car() {
super();
this.horsepower = 0;
this.isDriving = false;
this.needsMaintenance = false;
this.tripsSinceMaintenance = 0;
}
public int getHorsepower() {
return this.horsepower;
}
public boolean getDrive() {
return this.isDriving;
}
public boolean getMain() {
return this.needsMaintenance;
}
public int getTRIP() {
return this.tripsSinceMaintenance;
}
public void drive() {
this.isDriving = true;
}
public void stop() {
this.isDriving = false;
}
public void repair() {
this.needsMaintenance = false;
this.tripsSinceMaintenance = 0;
}
/**
* @param args
*/
public static void main(String[] args) {
Car auto = new Car();
auto.drive();
auto.stop();
if (auto.isDriving == true) {
if (auto.isDriving == false)
auto.tripsSinceMaintenance = auto.tripsSinceMaintenance + 1;
}
if (auto.tripsSinceMaintenance > 100)
auto.needsMaintenance = true;
System.out.println("Drive: " + auto.getDrive());
System.out.println("trip: " + auto.getTRIP());
}
}
我想要做的是每当属性isDriving 从true 变为false 时tripsSinceMaintenance should increase by 1 and also when tripsSinceMaintenanceis greater than 100,needsMaintenanceshould becometrue`。
这里我预计trips 是1,但结果如下:
驱动器:假 行程:0
我已经尝试过this.isDriving==true;,并且基本上auto 在我放入 this 的 if 语句中,但出现以下错误
不能从静态上下文中引用非静态变量
请帮帮我!
【问题讨论】:
-
您有两个嵌套的
if语句。仔细检查每个语句的条件以及它们如何相互作用。 -
auto.isDriving 不能同时为真和假
-
@OldProgrammer 你是完全正确的谢谢!!!!
标签: java if-statement counter