Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在二维数组中搜索任何索引?_Java_Arrays - Fatal编程技术网

Java 如何在二维数组中搜索任何索引?

Java 如何在二维数组中搜索任何索引?,java,arrays,Java,Arrays,所以我正在制作一个程序,它接受一个5x5的2D数组,并列出数组中任何给定索引周围的所有字符。例如,如果我输入列表[1][1],它将给出索引:[0][0]、[0][1]、[0][2]、[1][0]、[1][2]、[2][0]、[2][1]、[2][2] 我可以打印出索引周围的所有字母,除了边缘上的字母,如索引[0][0]。我似乎想不出如何克服这一点 private static void checkSurrounding(char[][] list, int x, int y) { fo

所以我正在制作一个程序,它接受一个5x5的2D数组,并列出数组中任何给定索引周围的所有字符。例如,如果我输入列表[1][1],它将给出索引:[0][0]、[0][1]、[0][2]、[1][0]、[1][2]、[2][0]、[2][1]、[2][2]

我可以打印出索引周围的所有字母,除了边缘上的字母,如索引[0][0]。我似乎想不出如何克服这一点

 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]);
            }
        }
    } 
}
private static void checkaround(char[][]列表,int x,int y){

对于(int dx=-1;dx而言,您的代码几乎正确!您排除了中间点:

 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]);
            }
        }
    } 
}
private static void checkaround(char[][]列表,int x,int y){

对于(int dx=-1;dx)是否有输出意外的输入示例?当我将x和y作为(0,0)输入时,或在边上创建索引的任何值时,它在线程“main”中返回:Exceptionjava.lang.ArrayIndexOutOfBoundsException:-1如果
x
为10000,您认为会发生什么?您必须同时执行上限和下限检查如果输入是边,预期的行为是什么?它是否会提供较少的输出、环绕到另一侧或其他什么?我是否必须为边的每一侧提供不同的边界d检查?啊,这很有效!我不知道如何确保我没有越界,谢谢你!@RandomJavaCoder欢迎你,最重要的是确保你知道你的解决方案几乎是正确的。当然你是个初学者,但你离解决方案不远。如果我的答案解决了你的问题,那么你就错了考虑把它标记为正确答案。
 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]);
                }
            }
        }
    } 
}