How to break out of loops in a Menu/Sub-Menu

418 views Asked by At

I have a CRUD program that I am making that allows a user to create a Shoppingcart and input Product items into it. I have two menus: the basic CRUD screen that will contain an ArrayList of Carts, and a sub-menu that creates one Cart, allows a user to input Products into it, and returns a Cart when it is finished. My problem is how to break out of the while loop in the submenu that continues to allow them to enter Products into the Cart, and return back to the CRUD main menu.

public static Cart subMenu() {
    boolean exit = false;
    Scanner input = new Scanner(System.in);
    Product myFruit;
    String name;
    int quantity;
    Cart myCart = new Cart();

    while (!exit) {
        System.out.println("Please enter an item and a quantity. Enter Q to return");
        name = input.next();
        quantity = input.nextInt();
        myFruit = new Product(name, quantity);
        myCart.addToCart(myFruit);
        System.out.println(myCart.getList());
        System.out.println(myCart.getTotal());
        if (name.equalsIgnoreCase("Q")) {
            exit = true;
        }

    }
    return myCart;
}
1

There are 1 answers

0
AngelTrs On

Use break; , as in the following example:

while (true) {
....
if (name.equalsIgnoreCase("Q"))
{
   break;
}

....
}

Source / More Info: http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html