I want to create 2D array in java with given scanner input.
1 3
2
3
-1
and the result will be like that [[1,2],[3],[3],[-1]].
I tried with following one unfortunately, it was still not correct. Please let me know how to do it, thanks.
Scanner sc = new Scanner(System.in);
int nodes[][] = new int[4][2];
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 2; j++) {
nodes[i][j] = sc.nextInt();
}
}
>Solution :
Read an entire line. Then split the line on space. The size of the array is the number of items. Create the sub-array using that length:
int nodes[][] = new int[4][];
for(int i = 0; i < 4; i++) {
String[] s = sc.nextLine().split(" ");
nodes[i] = new int[s.length];
for(int j = 0; j < s.length; j++) {
nodes[i][j] = Integer.parseInt(s[j]);
}
}