Graham Warrender
Graham Warrender

Reputation: 365

Prevent values going outside a specified range

private int currentSpeed;
private static final int MAXIMUM_SPEED = 100;
private int heading;

int speedUp(int increaseBy) {

    currentSpeed += increaseBy;

    return currentSpeed;
}

int slowDown(int decreaseBy) {

    currentSpeed -= decreaseBy;

    return currentSpeed;
}

How can i prevent the value currentSpeed from exceeding the MAXIMUM_VALUE variable in the speedUp method, and also from dropping below 0 in the slowDown method without using an if statement. I believe using Math.min & Math.max would work, but i'm unsure how to implement.

Upvotes: 0

Views: 97

Answers (2)

StackFlowed
StackFlowed

Reputation: 6816

You should be able to it using ternary operator

int speedUp(int increaseBy) {
    currentSpeed = currentSpeed + increaseBy < MAXIMUM_SPEED ? currentSpeed += increaseBy : MAXIMUM_SPEED;
    return currentSpeed;
}

int slowDown(int decreaseBy) {
    currentSpeed = currentSpeed - decreaseBy > 0 ? currentSpeed -= decreaseBy : 0;
    return currentSpeed;
}

Upvotes: 0

BatScream
BatScream

Reputation: 19700

Use Math.max and Math.min as below:

int speedUp(int increaseBy) {
    currentSpeed = Math.min(currentSpeed + increaseBy,MAXIMUM_SPEED);
    return currentSpeed;
}

int slowDown(int decreaseBy) {
    currentSpeed = Math.max(currentSpeed - decreaseBy,0);
    return currentSpeed;
}

Upvotes: 5

Related Questions