David February 2016

Understanding nested loop and classes

I started a project to understand deeply nested loops and classes. In my CYCLING method when I reach the if(y >= 0) loop it doesn't properly use my variables in classes. For example if MPH is 15 and the gear is 1 or 3 it won't ask me to change gear. Or if gear is 1 and speed is 11+ it wont ask me to change gear? What am I doing incorrectly?


public class Bike {
    int speed;
    int gear;

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

    void speedUp(int newVal) {
        speed = newVal;
    }

    void breaks(int slow) {
        speed = speed + slow;
    }

    void printState() {
        System.out.println("Gear is: " + gear);
        System.out.println("Speed is: " + speed + ("MPH"));
    }
}

//________________________

public static boolean cycle = true;
public static Bike b1 = new Bike();
public static int x;
public static int y;
public static Scanner input = new Scanner(System.in);
public static int choice;

//______________________________

public static void cycling() {
    while (cycle == true) {
        System.out.println("What would you like to do now? Enter a number.");
        System.out.println("1: Speed Change");
        System.out.println("2: Change Gear");
        choice = input.nextInt();
        if (choice == 1) {
            System.out.println("Choose a speed change");
            y = input.nextInt();
            if (y < 0) {
                b1.breaks(y);
                if (b1.speed < 0) {
                    b1.speed = Math.abs(y) + y;
                    System.out.println("You've stopped entirely");
                }
            }
            if (y >= 0) {
                b1.speed = y;
                b1.printState();
                if (b1.speed >= 0 && b1.speed <= 10) {
                    while (b1.gear != 1) {
                        System.out.println("You need to be in Gear 1 for " + "that! Please change gears.");
                        x = input.nextInt();
                   

Answers


John February 2016

Think about your statements. You have something that basically looks like this:

if (b1.speed >= 0 && b1.speed <= 10) {
    //some while loop here to do whatever
    if (b1.speed >= 11 && b1.speed <= 20) {
        //more code
    }
}

In your code, this statement will never be true:

if (b1.speed >= 11 && b1.speed <= 20) {

The only way you get to that statement is if b1.speed>=0 && b1.speed<=10. Therefore, will b1.speed ever be between 11 and 20 when you get to that second (nested) if statement?

Post Status

Asked in February 2016
Viewed 1,852 times
Voted 4
Answered 1 times

Search




Leave an answer