+ 2

Please explain this program

public class Program { public static void main(String[] args) { int[ ][ ] myArr = { {1, 2, 3}, {4}, {5, 6, 7} }; myArr[0][2] = 42; int x = myArr[1][0]; System.out.println(x); } }

17th Mar 2019, 12:49 AM
Priyanka Gotugade.
Priyanka Gotugade. - avatar
8 Respuestas
+ 2
myArr is a multidimensional array. (There are three arrays inside an array) 0 --> first array 0,0 = 1 0,1 = 2 0,2 = 3 1 --> second array 1,0 = 4 2 --> third array 2,0 = 5 2,1 = 6 2,2 = 7 myArr[0][2] = 42 //change the value at [0][2] // myArr now:{ {1,2,42},{4},{5,6,7} } int x = myArr[1][0]; //x gets the value from [1][0] --> 4 System.out.println(x); //output 4
17th Mar 2019, 1:07 AM
Denise Roßberg
Denise Roßberg - avatar
+ 2
Priyanka G myArr[0][2] = 42 could be an example to show you that you can change a value inside an array.
17th Mar 2019, 1:14 AM
Denise Roßberg
Denise Roßberg - avatar
+ 2
Priyanka G It is an example: " You can get and set a multidimensional array's elements using the same pair of square brackets." (The text above the code explains it) https://www.sololearn.com/learn/Java/2149/?ref=app
17th Mar 2019, 1:17 AM
Denise Roßberg
Denise Roßberg - avatar
+ 1
But why myArr[1 ] [ 2]=42; they are use in program
17th Mar 2019, 12:57 AM
Priyanka Gotugade.
Priyanka Gotugade. - avatar
+ 1
Rictus thx. A typo. I changed it.
17th Mar 2019, 1:11 AM
Denise Roßberg
Denise Roßberg - avatar
0
You output a number from an array made of arrays : x is 4
17th Mar 2019, 12:52 AM
Isaac Perez
Isaac Perez - avatar
0
the “myArr[0][2] = 42” line means that from the first (Java arrays start counting from cero) array, we take the third value, 3, and change its value to 42, at this point of the code it really doesn’t change much to the output as we are printing 4(Which is [1][0]), not 42(Which is [0][2]). Hope that helped.
17th Mar 2019, 1:01 AM
Isaac Perez
Isaac Perez - avatar
0
Denise, I think in the first array 3 is 0,2 not 0,3
17th Mar 2019, 1:09 AM
Isaac Perez
Isaac Perez - avatar