When I was learning to get java Silver, I'm stuck at the initialization of the multidimensional array, so I'll leave it as a memo.
String[][] array = {{"a","b"},{"c","d","e"},{"f","g","h","i"}};
I wrote [] []
when declaring an array, but I was confused because the number of parentheses did not correspond to {} {} {}
.
I couldn't understand why this array would compile ...
It was a simple story.
String[][] array = {{"array[0][]"},{"array[1][]"},{"array[2][0]"}};
The three {} correspond to the subscript part of the first-dimensional array, The values of a to i described in {} were the values of the second-dimensional array referenced by the first-dimensional array.
public class Main{
public static void main(String[] args) {
String array[][] = {{"a","b"},{"c","d","e"},{"f","g","h","i"}};
System.out.println(array[0][0]); //a
System.out.println(array[0][1]); //b
System.out.println(array[1][0]); //c
System.out.println(array[1][1]); //d
System.out.println(array[1][2]); //e
System.out.println(array[2][0]); //f
System.out.println(array[2][1]); //g
System.out.println(array[2][2]); //h
}
}
When I actually output each element with the println method, the expected result was returned.
By the way, when actually outputting each element of the array,
public class Main {
public static void main(String[] args) {
String array[][] = { { "a", "b" }, { "c", "d", "e" }, { "f", "g", "h", "i" } };
for(String[] tmp : array) {
for(String s : tmp) {
System.out.println(s);
}
}
}
}
In this way, the method of turning an array using a for statement is more common.
Readability is not good for the 3rd and subsequent dimensions, but it is possible to nest and output each element as shown below.
public class Main {
public static void main(String[] args) {
String array[][][] = { { { "a", "b" }, { "c", "d", "e" } }, { { "f", "g", "h", "i" }, { "j", "k", "l", "m" } },
{ { "n", "o", "p" }, { "q" } } };
for (String[][] s1 : array) {
for (String[] s2 : s1) {
for (String s3 : s2) {
System.out.println(s3);
}
}
}
}
}
Recommended Posts