FoodMonster
FoodMonster

Reputation: 1

Try-Catch help. How do i loop

For the second part, where it says new order, if i put '5' it would say "please choose a valid option" and loop back to the "Welcome to Foot----" part.

How do i get it to only loop back to where they entered the prompt wrongly?

For example: if i enter 5, it would say "Please choose valid option" and then display the "new order" part and not the "Welcome---"

public static void main(String[] args) {
        Assignment2A_JasmineLimSmithh myref = new Assignment2A_JasmineLimSmithh();
        while (true) {
        myref.run();
    }
    }
    void run() {
        System.out.println("Welcome to Foot Loose Reflexology");
        System.out.println("Main Menu \n 1. add new order \n 2. update order \n 3. view all orders \n 4. exit");
        System.out.print("Enter your choice [1...4] ");
        int a = 0;

        try {
            a = scan.nextInt();
        } catch (Exception e) {
            System.out.println("Please choose a valid option!");
            return;
        }

        if (a > 4 || a < 1) {
            System.out.println("Please choose a valid option!");
            return;
        }
        if (a == 1)
            newOrder();
        else if (a == 2)
            updateOrder();
        else if (a == 3)
            displayOrders();
        else if (a == 4)
            System.exit(0);
    }
void newOrder() {
        int name, choices = 0, duration = 0, order;
        System.out.println();
            do { // check for space?
                System.out.println("Add new order \n Reflexologist name: \n 1. Mark \n 2. James \n 3. Lily");
                System.out.print("Enter your choice [1...3] ");

                try {
                    name = scan.nextInt();
                } catch (Exception e) {
                    System.out.println("Please choose a valid option!");
                    return;
                }

                if (name > 3 || name < 1) {
                    System.out.println("Please choose a valid option!");
                    return;
                }

            } while (name > 3 || name < 1);

Upvotes: 0

Views: 47

Answers (1)

duppydodah
duppydodah

Reputation: 195

Get rid of the return in the inner if statement

        do { // check for space?
            System.out.println("Add new order \n Reflexologist name: \n 1. Mark \n 2. James \n 3. Lily");
            System.out.print("Enter your choice [1...3] ");

            try {
                name = scan.nextInt();
            } catch (Exception e) {
                System.out.println("Exception - wrong input type");
                return;
            }

            if (name > 3 || name < 1) {
                System.out.println("Please choose a valid option!");
                // return; <-- removed
            } 

        } while (name > 3 || name < 1);

Upvotes: 1

Related Questions