如何在此解决方案中打印出不带“]”的 3d 数组

how to print out 3d arrays without ']' in this solution

好像每一关结束后都留有右括号; 9、19、29 之后

控制台截图:https://imgur.com/a/ezcUdWq


//2d part
        int[][] a2D_array = {{1, 2, 3}, {4,5,6}, {7,8,9}};

        System.out.println(Arrays.deepToString(a2D_array)
            .replace("], ", "\n")
            .replace(", ", " ")
            .replace("[[", "")
            .replace("]]", "")
            .replace(",", " ")
            .replace("[", "")
        );

        System.out.println("\nThe element from the given input is: "+a2D_array[2][0]);

//3d part

        int [][][]a3D_array = {{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, {{11, 12, 13}, {14, 15, 16}, {17, 18, 19}}, {{21, 22, 23}, {24, 25, 26}, {27, 28, 29}}};
        System.out.println(Arrays.deepToString(a3D_array)
                .replace("], ", "\n")
                .replace(", ", " ")
                .replace("[[", "")
                .replace("]]", "")
                .replace("]],", "")
                .replace(",", " ")
                .replace("[", "")
        );

        System.out.println("\nThe element from the given input is: "+a3D_array[2][1][1]);

a3D_array的输出是:

1 2 3

4 5 6

7 8 9]

11 12 13

14 15 16

17 18 19]

21 22 23

24 25 26

27 28 29]

您需要考虑开始时的输入,

[[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[11, 12, 13], [14, 15, 16], [17, 18, 19]], [[21, 22, 23], [24, 25, 26], [27, 28, 29]]]

以及替换操作的应用顺序。

您可能认为,既然您有 ]], 的替换项,它将覆盖 9 之后的那三个字符。但是,当它到达那个替换时,您的第一个替换已经带走了 ], ,这样您在 9 之后只有一个 ]。您没有单个 ] 的替换。顺序很重要。替换操作按指定顺序依次进行。

在继续之前,我会提到一个更有效的解决方案是避免使用 deepToString 并完全替换,并使用简单的 for 循环来迭代数组并使用完全相同的字符填充 StringBuilder你想要的。

然而,如果你必须用deepToString/replace解决它,我建议从逻辑上分解问题并首先替换最长的模式。例如,

.replace("]], ", "\n").replace("]]]", "\n") // divide into 2d arrays with a line break between
.replace("], ", "\n") // divide into 1d arrays with a line break between
.replace("[", "").replace(",", "").replace("]", "") // remove remaining unwanted characters

在我看来,一次打印出数组一个元素要简单得多。

  1  2  3
  4  5  6
  7  8  9
 11 12 13
 14 15 16
 17 18 19
 21 22 23
 24 25 26
 27 28 29

这是完整的可运行代码。

public class Print3DArray {

    public static void main(String[] args) {
        int[][][] a3dArray = { { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } },
                { { 11, 12, 13 }, { 14, 15, 16 }, { 17, 18, 19 } },
                { { 21, 22, 23 }, { 24, 25, 26 }, { 27, 28, 29 } } };

        for (int i = 0; i < a3dArray.length; i++) {
            for (int j = 0; j < a3dArray[i].length; j++) {
                for (int k = 0; k < a3dArray[i][j].length; k++) {
                    System.out.print(String.format("%3d", a3dArray[i][j][k]));
                }
                System.out.println();
            }
        }

    }

}