Michael Michael - 21 days ago 6
Java Question

Increase and decrease a variable until a number is reached in java

I have this class:

public class Vehicle {
private float speed;

public void Acceleration()
{
++speed;
}
}


Each time
Acceleration
method have been called
speed
variable increase by one.

I need to change
Acceleration
method this way that, if
speed
variable reached to value 10 and
Acceleration
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).

Answer

It seems like a silly question, but just using the divide operator one can go with something like

public void Acceleration()
{
    speed += (1 - (int) (speed / 10));
}

The expression (int) (speed / 10) is equal to zero until speed reaches 10, when it becomes 1.