这是我的代码。
try{
if("**".equals(state[i][j-1])){
state[i][j-1] = String.valueOf(stopState);
stopState++;
willBeInitialized[i][j-1] = true;
}
if("**".equals(state[i+1][j-1])){
state[i+1][j-1] = String.valueOf(stopState);
stopState++;
willBeInitialized[i+1][j-1] = true;
}
if("**".equals(state[i+1][j])){
state[i+1][j] = String.valueOf(stopState);
stopState++;
willBeInitialized[i+1][j] = true;
}
if("**".equals(state[i][j+1])){
state[i][j+1] = String.valueOf(stopState);
stopState++;
willBeInitialized[i][j+1] = true;
}
if("**".equals(state[i-1][j+1])){
state[i-1][j+1] = String.valueOf(stopState);
stopState++;
willBeInitialized[i-1][j+1] = true;
}
if("**".equals(state[i-1][j])){
state[i-1][j] = String.valueOf(stopState);
stopState++;
willBeInitialized[i-1][j] = true;
}
}catch(Exception a){
//continue next if statements;
}
我应该在捕获范围内写什么? 或者我是否应该重写声明?怎么样?
答案 0 :(得分:0)
简单的答案是,你没有;如果您希望代码的一部分中的异常不会导致跳过另一部分,则必须将它们放在不同的try块中。但是,在您的情况下,有一个优雅的解决方案,循环使用单个代码块表示许多不同的try块:
for (int k = i - 1; k <= i + 1; k++) {
for (int l = j - 1; l <= j + 1; l++) {
if (l - j == k - i) continue;
try {
if("**".equals(state[k][l])){
state[k][l] = String.valueOf(stopState);
stopState++;
willBeInitialized[k][l] = true;
}
} catch (Exception e) {
//do nothing, loop to next try block
}
}
}
答案 1 :(得分:0)
我建议用较少的重复来重写代码。您一直在state
数组的不同单元格中检查相同的条件。所以我建议这样的事情:
for(k=i-1;k<i+1;k++){
for(l=j-1;l<j+1;l++){
try{
if("**".equals(state[k][k])){
state[k][l] = String.valueOf(stopState);
stopState++;
willBeInitialized[k][l] = true;
}
}catch(Exception e){
//Even if you get an exception while the if statement is evaluated,
//the loop will continue to execute the next if snippet
continue;
}
}
}
当然我不能保证这是你需要的片段,但我认为你得到了我提出的逻辑。
希望我帮忙!