Java - Best way to print 2D array?

前端 未结 12 624
庸人自扰
庸人自扰 2020-11-22 15:07

I was wondering what the best way of printing a 2D array was. This is some code that I have and I was just wondering if this is good practice or not. Also correct me in any

相关标签:
12条回答
  • 2020-11-22 15:52

    Try this,

    for (char[] temp : box) {
        System.err.println(Arrays.toString(temp).replaceAll(",", " ").replaceAll("\\[|\\]", ""));
    }
    
    0 讨论(0)
  • 2020-11-22 15:55

    Two-liner with new line:

    for(int[] x: matrix)
                System.out.println(Arrays.toString(x));
    

    One liner without new line:

    System.out.println(Arrays.deepToString(matrix));
    
    0 讨论(0)
  • 2020-11-22 15:55
    System.out.println(Arrays.deepToString(array)
                             .replace("],","\n").replace(",","\t| ")
                             .replaceAll("[\\[\\]]", " "));
    

    You can remove unwanted brackets with .replace(), after .deepToString if you like. That will look like:

     1  |  2  |  3
     4  |  5  |  6
     7  |  8  |  9
     10 |  11 |  12
     13 |  15 |  15
    
    0 讨论(0)
  • 2020-11-22 16:01

    Simple and clean way to print a 2D array.

    System.out.println(Arrays.deepToString(array).replace("], ", "]\n").replace("[[", "[").replace("]]", "]"));
    
    0 讨论(0)
  • 2020-11-22 16:03

    I would prefer generally foreach when I don't need making arithmetic operations with their indices.

    for (int[] x : array)
    {
       for (int y : x)
       {
            System.out.print(y + " ");
       }
       System.out.println();
    }
    
    0 讨论(0)
  • 2020-11-22 16:03

    From Oracle Offical Java 8 Doc:

    public static String deepToString(Object[] a)

    Returns a string representation of the "deep contents" of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings.

    0 讨论(0)
提交回复
热议问题