Two-dimensional arrays
A multidimensional array can simply be understood as nesting arrays in an array
The definition format of two-dimensional arrays
There are many ways to define a two-dimensional array
The first way
1 int New int [3] [4];
The above code is equivalent to defining a two-dimensional array of 3*4, where the length of the two-dimensional array is 3, and each element in a two-dimensional array is an array of length 4 .
The second way
1 int New int [3] [];
The second way is similar to the first, except that the length of each element in the array is indeterminate
The Third Way
1 int [] arr = {{1,2},{3,4,5,6},{7,8,9}};
Three elements are defined in the above two-dimensional array, all three elements are arrays, {},{3,4,5,6},{7,8,9}
Access to elements in a two-dimensional array is also done by means of a corner label, such as accessing the second element of the first element array in a two-dimensional array
1 arr[0][1];
Access to two-dimensional array elements
How to get the value of an element in a two-dimensional array
Cases:
1 classArrayDemo08 {2 Public Static voidMain (string[] args) {3 4 //How to define a two-dimensional array5 int[] arr =New int[3] [4];6 7 System.out.println (arr);8System.out.println ("Length of two-dimensional array:" +arr.length);9 //get 3 elements of a two-dimensional arrayTenSystem.out.println (arr[0] ); OneSystem.out.println (arr[1] ); ASystem.out.println (arr[2] ); - -System.out.println ("Print the element value of the first one-dimensional array"); theSystem.out.println (arr[0][0] ); -System.out.println (arr[0][1]);//The 2nd element of the 1th one-dimensional array in a two-dimensional array is accessed -System.out.println (arr[0][2] ); -System.out.println (arr[0][3] ); + -SYSTEM.OUT.PRINTLN ("prints element values of the second one-dimensional array"); +System.out.println (arr[1][0] ); ASystem.out.println (arr[1][1] ); atSystem.out.println (arr[1][2] ); -System.out.println (arr[1][3] ); - -SYSTEM.OUT.PRINTLN ("prints element values of the third one-dimensional array"); -System.out.println (arr[2][0] ); -System.out.println (arr[2][1] ); inSystem.out.println (arr[2][2] ); -System.out.println (arr[2][3] ); to}
Two-dimensional array element traversal and array element summation and
1 classArrayDemo09 {2 Public Static voidMain (string[] args) {3 //summation and traversal of one-dimensional arrays4 int[] arr = {10,20,30,40,50};5 intsum = 0; 6 for(inti=0; i<arr.length; i++) {7 //System.out.println (Arr[i]);8Sum + =Arr[i];9 }TenSystem.out.println ("sum=" +sum); OneSystem.out.println ("---------------------"); A - //summation and traversal of two-dimensional arrays - int[] arr2 = {{1,2},{3,4,5},{6,7,8,9,10} }; the intsum2 = 0; - for(inti=0; i<arr2.length; i++) { - for(intj=0; j<arr2[i].length; J + +) { - //System.out.println (Arr2[i][j]) +Sum2 + =Arr2[i][j]; - } + } ASystem.out.println ("sum2=" +sum2); at } - } -Results: sum=150 -Sum2=55
Java two-dimensional array