在下面的if语句中,如果它为false,它将正确打印else语句。 "No order with this number exists, please create a new order."
如果它是真的,它也会正确打印第一个语句,但它后面总是跟着else
语句。为什么break;
在第一个案例打印后终止?
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
答案 0 :(得分: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.
}
答案 1 :(得分:0)
你不能在while()循环中打破一个案例。最直接的解决方法是在断开while时将boolean设置为true,在循环后检查它,如果为true则再次断开。