简化Java中连续的'if'语句 [英] Simplification of successive 'if' statements in Java
本文介绍了简化Java中连续的'if'语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一系列 if
语句,如下所示:
I have a series of if
statements, as shown below:
if (board[x+1][y]==true) {
ar+=1;
}
if (board[x][y+1]==true) {
ar+=1;
}
if (board[x-1][y]==true) {
ar+=1;
}
if (board[x][y-1]==true) {
ar+=1;
}
if (board[x+1][y+1]==true) {
ar+=1;
}
if (board[x+1][y-1]==true) {
ar+=1;
}
if (board[x-1][y+1]==true) {
ar+=1;
}
if (board[x-1][y-1]==true) {
ar+=1;
}
有没有办法用Java简化/压缩这些语句?
Is there a way to simplify/condense these statements with Java?
推荐答案
只需绕过你关心的位置。跳过框的中心。
Simply loop around the position that you care about. Skipping the center of the "box".
提示:您可以按行然后列或访问2D数组[y] [x]
(至少,这就是你如何通过查看代码来翻译董事会)。
Tip: You access a 2D array by row then column, or [y][x]
(at least, that's how you'd translate the board from looking at the code).
// int x, y; // position to look around
for (int xDiff = -1; xDiff <= 1; xDiff++) {
for (int yDiff = -1; yDiff <= 1; yDiff++) {
if (xDiff == 0 && yDiff == 0) continue;
if (board[y+yDiff][x+xDiff]) {
ar += 1;
}
}
}
小心 - 超出界限例外未处理
Beware - Out of bounds exception is not handled
这篇关于简化Java中连续的'if'语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文