Seems like after each level there is close bracket left at the end; after 9, 19, 29.
console screenshot: 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]);
The output of a3D_array is:
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]
CodePudding user response:
You need to consider the input that you are starting with,
[[[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]]]
and the order in which the replace operations are applied.
You might think that since you have a replace for ]], it will cover those three characters following 9. However, by the time it gets to that replace, your first replace has already taken away ], such that you only have a single ] following the 9. You don't have a replace for single ]. The order matters. The replace operations happen sequentially, each after the other, in the order specified.
Before going any further, I'll mention that a much more efficient solution would be to avoid deepToString and replace entirely, and use simple for loops to iterate the array and populate a StringBuilder with exactly the characters that you want.
However, if you must solve it with deepToString/replace, I'd recommend logically breaking up the problem and replacing the longest patterns first. For example,
.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
CodePudding user response:
It seems to me that it's much simpler to print out the array one element at a time.
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
Here's the complete runnable code.
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("=", a3dArray[i][j][k]));
}
System.out.println();
}
}
}
}
