Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrease a variable until a number is reached in java

Tags:

java

I have this class:

public class Vehicle {
    private float speed;

     public void decelerationSpeed()
     {
         --speed;
     }  
}

Each time decelerationSpeed method have been called speed variable decreased by one.

I need to change decelerationSpeed method this way that, if speed variable reached to zero and decelerationSpeed method have been called the speed value doesn't have to be changed.

In this tutorial I can't use if else or any other conditional operators(I think I have to manipulate with modulo and divide operations).

like image 635
Michael Avatar asked May 12 '26 04:05

Michael


1 Answers

We always want to subtract by one except when our speed is zero so the modulo operation is appropriate as 0 mod y is 0 while for any other number we want x mod y to result in 1. The modulo operation that fits these criteria is x % (x - 1) The two corner cases then are 1 and 2 where 1 would give modulus of 0 and 2 mod 1 would have no effect. So we exclude them from the possible set of values with preliminary addition and subsequent subtraction:

   public void decelerationSpeed()
     {
        speed = speed + 2;
        speed = speed - ((speed) % (speed-1));
        speed = speed - 2;
     }
like image 53
Anatoly Avatar answered May 13 '26 19:05

Anatoly