首页 > 解决方案 > 如果语句不更新同一类中的私有字段

问题描述

所以我有这个类的代码:

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);

预期输出:

实际输出:

标签: javaif-statement

解决方案


当速度为负时,您减去一个负数,这与添加一个正数相同:

// When speed is negative, this corresponds to adding 
// the absolute value of speed to velocity
velocity -= speed;

您应该添加此负数。只有打印语句应该在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;
}

最好的


推荐阅读