Java If语句不更新同一类中的私有字段
我从课堂上得到了以下代码:Java If语句不更新同一类中的私有字段,java,if-statement,Java,If Statement,我从课堂上得到了以下代码: private int velocity = 0; public void velocityManagement(int speed){ if (speed > 0){ System.out.println("Pressing gas pedal"); velocity += speed; System.out.println("Velocity increased to
private int velocity = 0;
public void velocityManagement(int speed){
if (speed > 0){
System.out.println("Pressing gas pedal");
velocity += speed;
System.out.println("Velocity increased to " + velocity + " km/h");
} else{
System.out.println("Pressing break");
velocity -= speed;
System.out.println("Velocity decreased to " + velocity + " km/h");
}
这就是我在主类中使用它的方式:
car.velocityManagement(10);
car.velocityManagement(15);
car.velocityManagement(-20);
预期产出:
- 踩油门
- 速度增加到10公里/小时
- 踩油门
- 速度增加到25公里/小时
- 压断
- 速度降至5公里/小时
- 踩油门
- 速度增加到10公里/小时
- 踩油门
- 速度增加到25公里/小时
- 压断
- 速度降至45公里/小时
// When speed is negative, this corresponds to adding
// the absolute value of speed to velocity
velocity -= speed;
你应该加上这个负数。只有print语句应该出现在if-else
语句中
public void velocityManagement(int speed){
if (speed > 0){
System.out.println("Pressing gas pedal");
System.out.println("Velocity increased to " + velocity + " km/h");
} else{
System.out.println("Pressing break");
System.out.println("Velocity decreased to " + velocity + " km/h");
}
velocity += speed;
}
最好的@WojtekT在我点击标签时点击错误。对不起,因为负号…总是:速度+=速度;因为10+-10=0;)