如果语句未更新同一类中的私有字段

Adr*_*ian -1 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 " + velocity + " km/h");
        } else{
            System.out.println("Pressing break");
            velocity -= speed;
            System.out.println("Velocity decreased to " + velocity + " km/h");
        }
Run Code Online (Sandbox Code Playgroud)

这就是我在主类中使用它的方式:

car.velocityManagement(10);
car.velocityManagement(15);
car.velocityManagement(-20);
Run Code Online (Sandbox Code Playgroud)

预期产量:

  • 踩油门踏板
  • 速度提高到10 km / h
  • 踩油门踏板
  • 速度提高到25 km / h
  • 压破
  • 速度降至5 km / h

实际输出:

  • 踩油门踏板
  • 速度提高到10 km / h
  • 踩油门踏板
  • 速度提高到25 km / h
  • 压破
  • 速度降至45 km / h

Max*_*lle 6

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

// When speed is negative, this corresponds to adding 
// the absolute value of speed to velocity
velocity -= speed;
Run Code Online (Sandbox Code Playgroud)

您应该添加此负数。语句上只能有打印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;
}
Run Code Online (Sandbox Code Playgroud)

最好