在不同的行上打印二维数组

时间:2018-10-08 12:04:59

标签: java arrays

我正在尝试打印具有5行5列的二维数组,但是当我打印它时,我得到的行是“ [[0,0,0,0,0],[0,0, 0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]“如何打印我得到一个5x5的网格?

import java.util.Arrays;

public class spil {
    public static void main(String[] args) {
        int[][] grid=new int [5][5];

        System.out.println(Arrays.deepToString(grid));
    }

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

3 个答案:

答案 0 :(得分:1)

对此进行检查;

   import java.util.Arrays;

   public class spil {

    public static void main(String[] args) {

    int[][] grid=new int [5][5];
    print(grid);// you never called your function
   // System.out.println(Arrays.deepToString(grid));-----> This function was making all printing
}

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

答案 1 :(得分:0)

您在第7行呼叫Arrays::deepToString,而不是自定义的print方法。

相反,请使用print(grid);来调用您的方法。

答案 2 :(得分:0)

您可以仅调用您的打印方法:

public class Spil { 

   public static void main(String[]  args) {
      int[][] grid = new int[5][5]; 

      print(grid);
   } 

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

输出将是这样的:

0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
相关问题