java 的新手卡在 java 的决策中

New to java stuck on Decision Making in java

我创建了一个名为 class 的 Bicycle 现在我想将我的自行车的档位限制为 6。大于 6 的值会报错并显示消息:

System.out.println "Error...!! Please enter a number between 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();
            } 
        }

改变

void changeGear(int newValue) {
    gear = newValue;
}

void changeGear(int newValue) {
    if (newValue < 1 || newValue > 6) {
        System.out.println("Error...!! Please enter a number between 1-6");
    } else {
    gear = newValue;
    }
}
void changeGear(int newValue) {
   if(newValue < 1 || newValue > 6)
     throw new IllegalArgumentException("Please, enter a number between 1-6");
   else gear = newValue;
 }

void changeGear(int newValue) {
   if(newValue < 1 || newValue > 6)
     System.out.println("Please, enter a number between 1-6");
   else gear = newValue;
 }

你可以抛出一个异常,这是一个实际的错误,或者只是执行你的代码并将消息打印到控制台,唯一的区别是一旦满足条件,异常就会停止所有进一步的执行(取决于你的逻辑)。但这几乎就是 aconnelly 已经提到的内容。