在正确的时间从Switch断开

时间:2015-06-05 03:41:25

标签: java switch-statement break

我正在对河内塔进行一种非递归的方法。我知道...... 1)我们将第一个磁盘移动到下一个可用空间(这不是磁盘所在的最后/当前位置)。 2)移动下一个可能的磁盘(不是第一个磁盘)。 3)重复。我的系统包含List Stack个(这些是标尺),每个Stack包含Disk个对象。

问题:只有在breakSwitch被执行后,if catch怎么办?请注意,如果第一个tryif,则必须可以访问第二个false

switch(i){
  case 0: {
    try {
      if(gameObject.get(i).peek().getName() < 
         gameObject.get(i+1).peek().getName()){
// Move disk (i) to Stack (i+1) and exit switch.
      }
    } catch(EmptyStackException e){
// Move disk (i) to Stack (i+1) and exit switch. 


       }
    try {
      if(gameObject.get(i).peek().getName() < 
         gameObject.get(i+2).peek().getName()){
// Move disk (i) to Stack (i+2) and exit switch.
      }
    } catch(EmptyStackException e){
// Move disk (i) to Stack (i+2) and exit switch.                   
      }
  }
}

1 个答案:

答案 0 :(得分:2)

您应该将整个开关块封装在try catch块中,这里不必要地复制代码。这也意味着如果发现异常,它将自动从交换机中断开。

如果你想让if语句中断开关执行,只需要包含一个中断:

    int j;
    try {
        switch(i) {
            case 0:
                for(j = 1; j < 3; j++) {
                    if(gameObject.get(i).peek().getName() < 
                       gameObject.get(i+j).peek().getName()){
                        // do something
                        break;
                    }
                }
            default: 
                // do something
        }
    } catch (EmptyStackException e) {
        int peekThatFailed = j;  //Showing you can use j to determine which peek failed.
    }

编辑:可以在switch case中使用for循环来简化连续的if语句并跟踪索引偷看。