在正确的时间脱离 Switch
Breaking from Switch at the right time
我正在对河内塔进行一种非递归方法。我知道... 1) 我们将第一个磁盘移动到下一个可用的 space(这既不是磁盘所在的 last/current 位置)。 2)移动下一个可能的磁盘(不是第一个磁盘)。 3)重复。我有一个由 List
个 Stack
组成的系统(这些是杆),每个 Stack
持有 Disk
个对象。
问题:只有在 if
或 catch
执行后,我如何才能 break
Switch
?请记住,如果第一个 if
是 false
.
,则第二个 try
必须可以访问
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.
}
}
}
您应该将整个 switch 块封装在一个 try catch 块中,您在这里没有必要重复代码。这也意味着如果捕获到异常,它将自动从 switch 中断。
如果您希望 if 语句中断 switch 执行,只需包含一个中断:
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 语句并跟踪已查看的索引。
我正在对河内塔进行一种非递归方法。我知道... 1) 我们将第一个磁盘移动到下一个可用的 space(这既不是磁盘所在的 last/current 位置)。 2)移动下一个可能的磁盘(不是第一个磁盘)。 3)重复。我有一个由 List
个 Stack
组成的系统(这些是杆),每个 Stack
持有 Disk
个对象。
问题:只有在 if
或 catch
执行后,我如何才能 break
Switch
?请记住,如果第一个 if
是 false
.
try
必须可以访问
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.
}
}
}
您应该将整个 switch 块封装在一个 try catch 块中,您在这里没有必要重复代码。这也意味着如果捕获到异常,它将自动从 switch 中断。
如果您希望 if 语句中断 switch 执行,只需包含一个中断:
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 语句并跟踪已查看的索引。