mardi 26 mars 2019

If statement not updating a private field in the same class

so I have this code from class:

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

That's how I use it in the main class:

car.velocityManagement(10);
car.velocityManagement(15);
car.velocityManagement(-20);

Expected output:

  • Pressing gas pedal
  • Velocity increased to 10 km/h
  • Pressing gas pedal
  • Velocity increased to 25 km/h
  • Pressing break
  • Velocity decreased to 5 km/h

Actual output:

  • Pressing gas pedal
  • Velocity increased to 10 km/h
  • Pressing gas pedal
  • Velocity increased to 25 km/h
  • Pressing break
  • Velocity decreased to 45 km/h

Aucun commentaire:

Enregistrer un commentaire