Home > Software engineering >  How to make the method run from the beginning Without using a Loop
How to make the method run from the beginning Without using a Loop

Time:06-18

The code in the main():

public static void main(String[] args) {
    int menu = menu();
    if (menu == 0) {
        System.out.print("End program");
    }
    if (menu == 1) {
    
    }
    if (menu == 2) {
        System.out.print("Enter the Capacity>");
        double capacity = sc.nextDouble();
        if (capacity <= 0) {
            System.out.println("Wrong input");
            menu = menu();
            
        }
    }
}

And this is the menu() method:

public static int menu() {
    System.out.println("0. End program");
    System.out.println("1. No Caps");
    System.out.println("2. Knapsack Problem");
    System.out.println("3. Count Ways");
    System.out.println("4. Merge Strings");
    System.out.println("5. Password Generator");
    System.out.print("Enter a digit 0-5>");
    int choice = sc.nextInt();
    if (choice > 5 || choice < 0) {
        System.out.println("Wrong input");
        return menu();
    }
    return choice;
}

My problem is that I need the program to run from the beginning in case if use enters capacity <= 0.

Right now it's only printing the menu, but after I choose a menu option it exits even if capacity <= 0. I.e. the program is not checking if capacity is smaller than 0 again.

How can I fix that?

I cannot use loops - that is the requirement of my assignment.

CodePudding user response:

Since you're not allowed to use loops, then you need to extract conditional logic into a separate method which will be called from the main().

Lets call it start(). In case when the user provides a negative capacity for the Knapsack Problem (option 2) we should invoke start() recursively.

public static void main(String[] args) {
    start();
}

public static void start() {
    int menu = menu();
    if (menu == 0) {
        System.out.print("End program");
    }
    if (menu == 1) {
    
    }
    if (menu == 2) {
        System.out.print("Enter the Capacity>");
        double capacity = sc.nextDouble();
        if (capacity <= 0) {
            System.out.println("Wrong input");
            start(); // calling `start()` recursively
        }
        System.out.println("Capacity: "   capacity);
    }
}

static int menu() {
    System.out.println("0. End program");
    System.out.println("1. No Caps");
    System.out.println("2. Knapsack Problem");
    System.out.println("3. Count Ways");
    System.out.println("4. Merge Strings");
    System.out.println("5. Password Generator");
    System.out.print("Enter a digit 0-5>");
    int choice = sc.nextInt();
    if (choice > 5 || choice < 0) {
        System.out.println("Wrong input");
        return menu();
    }
    return choice;
}
  • Related