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