Search code examples
switch-statementbreakexecution

Break out of switch statement execute one case


So basically, I am trying to get the switch statement to only execute one time. And not execute all of them. Assume the player has all of the keys in their inventory. I want only one case to execute and not go through all the cases. (I'd like to only see one execute)

public int[] allKeys = {1543, 1544, 1545, 1546, 1547, 1548};

if (player.getInventory().containsAny(allKeys)) {
                      for (int id : allKeys) {
                          switch(id) {
                          case 1543:
                              System.out.println("executed");
                              break;
                          case 1544:
                              System.out.println("executed");
                              break;
                          case 1545:
                              System.out.println("executed");
                              break;
                          case 1546:
                              System.out.println("executed");
                              break;
                          case 1547:
                              System.out.println("executed");
                              break;
                          case 1548:
                              System.out.println("executed");
                              break;
                            default:
                              System.out.println("error!");
                          }
                        }
                    }

Solution

  • Your switch does only do "one at a time" - it is the fact your switch is in a for loop that is causing you problems...

    You could put a "break" after the switch switch(x) { ... } break;, but really why loop when you don't want to - just switch on say the first key.