Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to reduce vehicle speed without "if" statement

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading