Reputation: 93
6, 9
2, 5
4, 6
how to initialize these number in an 2D array?
this is my answer, but something with output.
int[][] num = new int [3][2];
num[0][0] = 6;
num[0][1] = 9;
num[1][0] = 2;
num[1][1] = 5;
num[2][0] = 4;
num[2][1] = 6;
System.out.println(num);
[[I@70f87478 (output)
Upvotes: 2
Views: 811
Reputation: 13073
When you do
System.out.println(num);
You will print the object's default ´toString` method, which prints the object's reference. TO print the contents, you can use 2 nested for-loops or a for-each loop.
Upvotes: 0
Reputation: 5399
Logic like in deepToString
int [][] test = new int[1][1];
StringBuilder builder = new StringBuilder();
for (int[] ints : test) {
builder.append(Arrays.toString(ints));
}
System.out.println(builder.toString());
Upvotes: 0
Reputation: 1504122
There's nothing wrong with that output, other than you're calling toString
on array and expecting to get something useful. If you use Arrays.deepToString()
instead, you'll get a more sensible result. (You'd normally only need Arrays.toString()
, but you need the "deep" version as it's an array of arrays.)
Additionally, you can initialize the array more compactly. Combining the two:
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[][] num = { { 6, 9 }, { 2, 5 }, { 4, 6 } };
System.out.println(Arrays.deepToString(num));
}
}
Output:
[[6, 9], [2, 5], [4, 6]]
Upvotes: 5
Reputation: 7996
int[][] num = {{6,9},{2,5},{4,6}}
System.out.println(Arrays.deepToString(num));
Upvotes: 1