Home > database >  How to reduce vehicle speed without "if" statement
How to reduce vehicle speed without "if" statement

Time:11-29

I have a vehicle class that gradually increases its speed to 10 and when it reaches 10 it maintains its value (remains 10), and when the speed is reduced, the speed must be reduced gradually. When it reaches 0, it maintains its value (remains 0).

I did not know how to reduce the vehicle speed and maintain the value (0), because the value becomes negative.

I know how to solve the problem through "if", but I want to solve it in a normal way as i did the speed increase to 10.

public class vehicle {

    private int speed;

    public void speedUp() {

        speed = (speed   1) - speed / 10;

    }

    public void slowDown() {



    }

    public void show() {

        System.out.println(speed);

    }

}

I tried this but when the value becomes "0" I get an error because a number cannot be divided by 0.

public void slowDown() {
        
    speed = (speed - 1) % (speed / -1 );
 
        
}

CodePudding user response:

You could return the maximum value between the speed and 0.

speed = Math.max((speed - 1), 0)

CodePudding user response:

In all cases but when speed is 0, you want speed = (speed - 1).

When speed is zero, you don't want speed to change, so you need to add one back. So you need an expression that evaluates to 1 when speed is zero and zero when speed is between 1 and 10 inclusive. That's (10 - speed) / 10.

Putting that together:

speed = (speed - 1)   (10 - speed) / 10;

CodePudding user response:

You could use the java ternary operator:

speed = speed != 0 ? (speed - 1) % (speed / -1) : 0;

CodePudding user response:

You want the Math.max and Math.min functions. Math.max(a,b) returns the bigger of a and b. Math.min(a,b) returns the smaller. So to make it not go above 10, you want Math.min(10, speed 1). To keep it at 0, do Math.max(0, speed - 1) This is actually better than the math you have above, as your math will break if there's ever a way to speed up by 2 at once, but Math.min and Math.max will continue to work.

  •  Tags:  
  • java
  • Related