Operation of an array: the most common operation is to iterate and get the elements in the array. In order to simplify the code, a for loop is generally used, and the traversal is typically used for loops
1 Public classArray_obtain {2 Public Static voidMain (string[] args) {3 int[] arr=New int[3];4 5 //gets the elements in the array6 for(intx=0;x<3;x++){7System.out.println ("arr[" +x+ "]=" +arr[x]+ ";");8 }9 }Ten}
If the array is in the second format then the array element is more than the case, with an attribute in the array (not the method) length, he can directly get to the array of the number of elements
The usage is: array name. length
1 Public classArray_obtain {2 Public Static voidMain (string[] args) {3 int[] arr=New int[]{4,56,7,8,9,3,25,56,32,345,43,5,3423,34};4 System.out.println (arr.length);5 intsum = 0;6 for(intU=0;u<arr.length; u++ ){7Sum + =Arr[u];8System.out.println ("arr[" +u+ "]=" +arr[u]+ ";");9 }TenSYSTEM.OUT.PRINTLN (sum);//gets the and of the element One } A - //defines the elements used to print an array, separated by commas between elements - Public Static voidPrintArray (int[] arr) { theSystem.out.print ("" "); - for(int× = 0;x<arr.length; x + + ) - { - if(x! = Arr.length-1) +System.out.print (arr[x]+ ","); - Else +System.out.println (arr[x]+ "" "); A } at } -}
Traversal of two-dimensional arrays:
Public classFortyeight { Public Static voidMain (string[] args) {//3 classes Each 4 participants, calculate the average score of each class intScores[][] =New int[3] [4]; Scanner input=NewScanner (system.in); for(inti = 0;i<3;i++){ for(intj = 0;j<4;j++) {Scores[i][j]=Input.nextint (); } } //outputs each element of a two-dimensional array for(inti = 0; i<3; i++) {System.out.println ("First" + (i+1) + "class student results:"); intsum = 0; for(intj = 0; j<4; J + +) {System.out.println (scores[i][j]); Sum+=Scores[i][j]; } System.out.println ("First" + (i+1) + "average Grade of Class:" + (SUM/4)); } }}
Array of common operations _ traversal