我创建了一个名为 Bicycle 的类,现在我想将自行车的档位限制为 6。大于 6 的值会出错并显示消息:
System.out.println“错误...!!请输入一个介于 1-6 之间的数字”。
有人可以告诉我需要做什么才能在下面提到的程序中获得所需的结果吗?对于Java中的决策,我需要在哪里声明条件以便执行?
public class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue) {
cadence = newValue;
}
void changeGear(int newValue) {
gear = newValue;
}
void speedUp(int increment) { speed = speed + increment; }
void applyBrakes(int decrement) { speed = speed - decrement;}
void printStates() {
System.out.println("cadence:" + cadence + " speed:" + speed + " gear:" + gear);
}
void vehicleType() {
System.out.println("Vehicle Type: Bicycle");
}
}
class BicycleDemo {
public static void main(String[] args) {
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
bike1.changeCadence(50);
bike1.applyBrakes(0);
bike1.changeGear(1);
bike1.printStates();
bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(20);
bike2.changeGear(4);
bike2.printStates();
}
}