0

in the below if statement if it's false it would print the else statement correctly. "No order with this number exists, please create a new order." and if it's true it prints the first statement correctly as well, but it's always followed by the else statement. Why isn't the break; terminating after the first if case is printed?

case(3):{ 
              System.out.println("");
            System.out.println("Please Enter The Order Number: ");
            int orderno = input.nextInt();
            Iterator<Order> orderIterator3 = orders.getIterator();
            Order currentorder;
            String itemRemoved = null;
            StackInterface <String> newItems = new ArrayStack<String>();
            while ( orderIterator3.hasNext()) { //iterate through the list until an order  with a matching order no is found 
                currentorder = orderIterator3.next();  
            if(currentorder.getNumber() == orderno) { //access the Items in the list by their order number 
                newItems = currentorder.getItems(); //Copy the existing items into a new stack
                if (!newItems.isEmpty())
                itemRemoved = newItems.pop();
                 System.out.println("The last item: " + itemRemoved + "\n was successfully removed from your order!"); break;
                }//End if

            }//End While 
            System.out.println("No order with this number exists, please create a new order."); break;
          }// End Case 3
helloworld
  • 173
  • 1
  • 2
  • 8

2 Answers2

3

When you break inside the while-loop, you will break the while-loop, not the case.

There are a few different ways of making this work, but the easiest would probably be to just add a boolean value that you set to true if it should break out of the case, something like:

boolean shouldBreak = false;
while( ... ) {
  if( ... ) {
    shouldBreak = true;
    break; // break out of the while.
  }
}
if(shouldBreak) {
  break; // break out of the switch/case.
} 
Jite
  • 5,761
  • 2
  • 23
  • 37
0

You can not break a case from inside a while() loop. The most straightforward fix is to set a boolean to true when breaking the while, check it after the loop, and break again if true.

Alex Nevidomsky
  • 668
  • 7
  • 14