我正在对河内塔进行一种非递归的方法。我知道...... 1)我们将第一个磁盘移动到下一个可用空间(这不是磁盘所在的最后/当前位置)。 2)移动下一个可能的磁盘(不是第一个磁盘)。 3)重复。我的系统包含List
Stack
个(这些是标尺),每个Stack
包含Disk
个对象。
问题:只有在break
或Switch
被执行后,if
catch
怎么办?请注意,如果第一个try
为if
,则必须可以访问第二个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.
}
}
}
答案 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语句并跟踪索引偷看。