+ 3
Multidimensional Arrays
In the lesson about arrays in Java, I don't understand how arrays work when you want an to use a multidimensional array. There's this code in the lesson : int[ ][ ] myArr = { {1, 2, 3}, {4}, {5, 6, 7} }; myArr[0][2] = 42; int x = myArr[1][0]; // 4 Why is myArr 42 ? Why is x 4 ? I know that arrays start from 0, so I would think "myArr[0][2]" reads the 1st value of the first array (here, "1") and the 3rd value of the second array, but the fact of having 3 curly brackets while there are 2 empty brackets makes my brain out.print "Error". Help please ! :)
3 Respuestas
+ 3
the first bracket reads the number of the array you want to look in, and the second one tells you which of the elements to choose. "outside to inside". and the 42 value just changes the value of the third element in the first array to 42.
+ 5
Basically, in the first example I.e. myArr[0][2] = 42; the code is simply changing the 3rd value of the first array (index 0) from 3 to 42. So if your try to print the 3rd value after this line, you won't get 3 but 42. The second code however is printing the first(and only) value of the second array(index 1) which is in this case 4. therefore the output is obviously 4.
+ 2
In fact you got an array of arrays here. So array [0] is [1,2,3], array [1] is [4], and array [2] is [5,6,7]. When you write in myArr you take array [0] and place number 42 on its third index so it becomes [1,2,42]. Same logic when you write a number from array in x too.