[英]How do you search around any index in a 2D array?
So I'm making a program that takes in a 2D array of 5x5, and lists all the characters around any given index of the array.所以我正在制作一个程序,它接收一个 5x5 的二维数组,并列出数组的任何给定索引周围的所有字符。 For example, if I input list[1][1], it will give the indexes: [0][0], [0][1], [0][2], [1][0], [1][2], [2][0], [2][1] ,[2][2].例如,如果我输入 list[1][1],它将给出索引:[0][0], [0][1], [0][2], [1][0], [1] ][2]、[2][0]、[2][1]、[2][2]。
I can print out all the letters around the indexes except for the ones on the edges such as index [0][0].我可以打印出索引周围的所有字母,但边缘的字母除外,例如索引 [0][0]。 I can't seem to figure out how to get past that.我似乎无法弄清楚如何克服这一点。
private static void checkSurrounding(char[][] list, int x, int y) {
for(int dx = -1; dx <= 1; dx++) {
for(int dy = -1; dy <= 1; dy++) {
if(!(dx == 0 && dy == 0)) {
System.out.print(list[x + dx][y + dy]);
}
}
}
}
Your code is almost correct!你的代码几乎是正确的! You exclude the middle point here:您在这里排除中间点:
private static void checkSurrounding(char[][] list, int x, int y) {
for(int dx = -1; dx <= 1; dx++) {
for(int dy = -1; dy <= 1; dy++) {
if(!(dx == 0 && dy == 0)) {
System.out.print(list[x + dx][y + dy]);
}
}
}
}
The only thing you miss is to avoid getting out of bounds.你唯一想念的是避免越界。 Just make sure that you do not get out of bounds and it should work impeccably:只要确保你没有越界,它应该可以完美地工作:
private static void checkSurrounding(char[][] list, int x, int y) {
for(int dx = -1; dx <= 1; dx++) {
if ((x + dx >= 0) && (x + dx < list.length)) {
for(int dy = -1; dy <= 1; dy++) {
if ((y + dy >= 0) && (y + yd < list[x + dx].length) && (!(dx == 0 && dy == 0))) {
System.out.print(list[x + dx][y + dy]);
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.