递归打印二维数组的问题

时间:2019-06-15 00:17:17

标签: java arrays

以递归方式打印2d数组时,该方法将打印出两列,并以三个额外的间距将第二列重复两次。我该如何解决?

完整代码:

public static void main(String [] args) {
    final int ROWS = 2, COLS = 2;
    long [][] arr = new long [ROWS][COLS];
    setArray(arr, 0, 0);

    System.out.println("Numbers in 2d Array: ");
    printArray(arr, 0, 0);

}

public static void setArray(long [][] a, int r, int c){
    if(r < a.length){
        if(c < a[r].length){
            a[r][c] = (long)(Math.random() * 100);
            setArray(a, r, ++c);
        }
        setArray(a, ++r, c = 0);
    }
}

public static void printArray(long [][]a, int r, int c){
    if(r < a.length){
        if(c < a[r].length){
            System.out.print(a[r][c] + " ");
            printArray(a, r, ++c);
        }
        System.out.println();
        printArray(a, ++r, c = 0);
    }
}

我遇到问题的方法:

public static void printArray(long [][] a, int r, int c){
    if(r < a.lenght){
        if(c < a[r].length){
            System.out.print(a[r][c] + " ");
            printArray(a, r, ++c);
        }
        System.out.println();
        printArray(a, ++r, c = 0);
    }
}

预期输出:

二维数组中的数字:

74 16

44 91

实际输出:

二维数组中的数字:

74 16

44 91

44 91

44 91

2 个答案:

答案 0 :(得分:1)

问题是当您在打印单个单元格值的第二条printArray()语句中时,没有退出if方法。这意味着,当您打印单个单元格值时,也将始终在末尾执行System.out.println();。这将导致许多新行和数组部分无效的输出。

System.out.println("Called with r="+r+",c="+c);方法的开头添加行printArray()时,将得到以下输出以用于调试:

Numbers in 2d Array: 
Called with r=0,c=0
89 Called with r=0,c=1
59 Called with r=0,c=2

Called with r=1,c=0
90 Called with r=1,c=1
71 Called with r=1,c=2

Called with r=2,c=0

Called with r=2,c=0

Called with r=2,c=0

Called with r=1,c=0
90 Called with r=1,c=1
71 Called with r=1,c=2

Called with r=2,c=0

Called with r=2,c=0

Called with r=2,c=0

Called with r=1,c=0
90 Called with r=1,c=1
71 Called with r=1,c=2

Called with r=2,c=0

Called with r=2,c=0

Called with r=2,c=0

从调试行可以看到,行索引和列索引并不是一直都在上升,而是从行索引2返回到索引1。这应该表明您的printArray();方法有什么问题。

要解决此问题,只需在第二个return;中使用if()语句即可尽早退出该方法(而不调用System.out.println();行)或使用if-else语句以打印单元格值 OR 或生成新行。

public static void printArray(long [][]a, int r, int c){
    if(r < a.length){
        if(c < a[r].length){
            System.out.print(a[r][c] + " ");
            printArray(a, r, ++c);
            return; //  <----------- here
        } // <--- or use an "else" block here
        System.out.println();
        printArray(a, ++r, c = 0);
    }
}

答案 1 :(得分:0)

看起来像一个作业问题。因此,我建议逐步执行以查找问题。如果您仍然陷于困境,我的提示是考虑何时返回。