为什么在打印第一个 if case 后 switch case 没有断开?

why is the switch case not breaking after the first if case is printed?

在下面的 if 语句中,如果它为假,它将正确打印 else 语句。 "No order with this number exists, please create a new order." 并且如果为真,它也会正确打印第一条语句,但它后面始终跟着 else 语句。为什么 break; 在打印第一个 if 情况后不终止?

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

当您在 while-loop 内部打断时,您会打断 while-loop,而不是 case

有几种不同的方法可以完成这项工作,但最简单的方法可能是添加一个布尔值,如果它不符合大小写,则将其设置为 true,例如:

boolean shouldBreak = false;
while( ... ) {
  if( ... ) {
    shouldBreak = true;
    break; // break out of the while.
  }
}
if(shouldBreak) {
  break; // break out of the switch/case.
} 

您不能从 while() 循环内中断 case。最直接的修复方法是在 break while 时将布尔值设置为 true,在循环后检查它,如果为 true 则再次 break。