防止超出指定范围的值

时间:2014-11-12 19:58:55

标签: java math max min

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

如何防止值currentSpeed超出speedUp方法中的MAXIMUM_VALUE变量,以及在slowDown方法中不使用if语句时降低0以下。我相信使用Math.min& Math.max可行,但我不确定如何实施。

2 个答案:

答案 0 :(得分:5)

使用Math.maxMath.min,如下所示:

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

答案 1 :(得分:0)

你应该能够使用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;
}