打印二维数组意外输出 java

Printing 2D array unexpected output java

我不确定代码是否有问题,因为每当我尝试 运行 它手动时它都能正常工作。有什么办法可以解决吗?

  1. 这是我的方法

    public static int[][] mystry2d(int[][] a){
    for(int r = 0; r<a.length; r++){
    for(int c=0; c<a.length-1;c++){
    if(a[r][c+1] > a[r][c]){
     a[r][c] = a[r][c+1] ;
       }
      }
     }
      return a ;
    }
    
  2. 我的打印方法

           public static void printArray(int[][] arr){ 
           for (int i=0;i<arr.length;i++){
           for(int j=0;j<arr[i].length;j++){ 
            System.out.print(arr[i][j]);
                           }
            System.out.println();
         }
     }
    

3.input 和预期输出

       **input:** int[][] numbers= {{3,4,5,6},{4,5,6,7},{5,6,7,8}};

       **output:** 4 5 6 6
                   5 6 7 7
                   6 7 8 8

4.output 当 运行 输入代码时

        4 5 5 6
        5 6 6 7
        6 7 7 8

所以,你正试图转动这个数组

3 4 5 6
4 5 6 7
5 6 7 8

进入

4 5 6 6
5 6 7 7
6 7 8 8

所以它基本上 "moves" 左边的值,但前提是新值大于以前的值。 但是,您的逻辑有一个缺陷:您在两个 for 循环中都使用 a.length 作为限制,假设数组是 "square",那么您正确地忽略了最后一列。然而,在 3x4 数组中,这使得算法仅适用于前两列,而不适用于第三列! 您应该寻找数组当前行的实际长度,以防止出现奇怪的错误。你的算法可能会变成:

public static int[][] mystry2d(int[][] a){
 for(int r = 0; r<a.length; r++){
  for(int c=0; c<a[r].length-1;c++){
   if(a[r][c+1] > a[r][c]){
    a[r][c] = a[r][c+1] ;
   }
  }
 }
 return a ;
}

请考虑缓存这个值,这样它就不会在每次迭代时都重新计算