【问题标题】:Printing 2D array unexpected output java打印二维数组意外输出java
【发布时间】:2019-02-01 10:45:11
【问题描述】:

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

  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:** 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.运行代码时的输出

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

【问题讨论】:

  • 我有点惊讶于代码甚至可以构建。你说mystry2d 应该返回一个int[][],但实际上你并没有返回任何东西。
  • 另外请阅读how to ask good questions,以及this question checklist。最后请学习如何创建一个minimal reproducible example 向我们展示。您如何使用您展示的功能?您最初是如何初始化数组的?
  • 预期输出背后的逻辑是什么?它总是应该跳过第一个元素吗?
  • 你调试mystry2d了吗?它应该做什么?
  • public static void main(String [] args){ int[][] numbers= {{3,4,5,6},{4,5,6,7},{5, 6,7,8}}; int[][] a = mystry2d(数字);打印数组(一); }

标签: java arrays printing 2d


【解决方案1】:

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

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

进入

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

因此它基本上将值“移动”到左侧,但前提是新值大于以前的值。 但是,您的逻辑有一个缺陷:您在两个 for 循环中使用 a.length 作为限制,假设数组是“正方形”,那么您正确地忽略了最后一列。但是,在 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 ;
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 2012-11-08
    • 2018-09-30
    • 1970-01-01
    相关资源
    最近更新 更多