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
可行,但我不确定如何实施。
答案 0 :(得分:5)
使用Math.max
和Math.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;
}