gpt4 book ai didi

java - 递归打印二维数组的问题

转载 作者:行者123 更新时间:2023-12-02 09:46:36 25 4
gpt4 key购买 nike

当递归打印二维数组时,该方法打印出两列,并以三个额外间距重复第二列两次。我该如何解决这个问题?

整个代码:

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

最佳答案

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

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

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(); 方法出了什么问题。

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

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);
}
}

关于java - 递归打印二维数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56606371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com