[英]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 的 output 是:
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();
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.