我有一个如下所示的 if 语句:
if (pan[x + 1][y + 1].getBackground() == TeamColor &&
pan[x + 1][y].getBackground() == TeamColor &&
pan[x + 1][y -1].getBackground() == TeamColor &&
pan[x][y - 1].getBackground() == TeamColor &&
pan[x - 1][y - 1].getBackground() == TeamColor &&
pan[x - 1][y].getBackground() == TeamColor &&
pan[x - 1][y + 1].getBackground() == TeamColor &&
pan[x][y + 1].getBackground() == TeamColor) {
// do something
}
目标是检查当前 x 和 y 值周围的每个项目(在二维数组中)并确保它们的颜色正确。
我想有一种简单的方法可以做到这一点。我假设创建一个 for
循环会通过遍历每个项目来解决问题,但遗憾的是无法想出一种方法来执行此操作,因为这些项目并非全部按顺序排列。
注意:我在 stackoverflow 上发现了许多其他标题为“非常长的 if 语句的解决方案”的帖子,不幸的是它们使用不同的编程语言(例如 python、android 和 javascript)
注意 2:这不是 this 的副本邮政。这是一个字符串和正则表达式的问题,不幸的是不是我的问题的解决方案
希望有人能给出答案!
最佳答案
尝试这样的事情:
boolean match = true;
for (int dx = -1; match && (dx < 2); ++dx) {
for (int dy = -1; match && (dy < 2); ++dy) {
if (dx != 0 || dy != 0) {
match = pan[x+dx][y+dy].getBackground() == TeamColour;
}
}
}
if (match) {
// do something
}
基本上,您想检查每个方向的偏移量 -1、0 和 1,所以我们有两个 for
循环,每个循环都在一个维度上产生这些偏移量。然后我们检查对应于每个偏移量的数组元素,并使用 match
进行跟踪。变量。
请注意,与原始代码一样,这将在边界附近失败(例如,如果 x == 0
)。如有必要,可以修复此问题。
当然,也可以让循环遍历实际索引进行检查(例如 for (int x2 = x-1; x2 < x+2; ++x)
)。最终大同小异。
关于Java把长if语句改成for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44039187/