New to java stuck on Decision Making in java

58 views Asked by At

I have created a class named Bicycle now I want to limit the gear of my bicycle to 6. A value greater than 6 will give an error and message will be displayed:

System.out.println "Error...!! Please enter a number between 1-6".

Can someone tell me what needs to be done to get the desired result in the below mentioned program? And for Decision Making in java where do I need to declare the condition so it gets executed?

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

2

There are 2 answers

1
aconnelly On BEST ANSWER

Change

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

To

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

or

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

You can either throw an exception, which is an actual error or just execute your code and print the message to the console, the only difference is that an exception stops all further execution once the condition is met(depends on your logic). But is pretty much what aconnelly already mentioned.