Introduction to JAVA array (I)
So far, the basic syntax of java has been basically summarized. The next thing to learn is array.
1. Overview of Array
- Array is a collection of multiple data of the same type arranged in a certain order, named with a name, and managed uniformly by numbering.
- Common concepts of arrays:
1. Array name
2. Elements
3. Corner mark, subscript and index
4. Length of array: the number of elements - Array features:
1. The array is arranged in order
2. The array is a variable of reference data type. The element of an array can be either a basic data type or a reference data type
3. Creating an array object will open up a whole block of continuous space in memory
4. Once the length of the array is determined, it cannot be modified - Classification of arrays:
1. According to dimension: one-dimensional array, two-dimensional array....
2. According to the type of array elements: array of basic data type elements and array of reference data type elements - Use of one-dimensional array:
1. Declaration and initialization of one-dimensional array
2. How to call the element at the specified position of the array
3. How to get the length of the array
4. How to traverse an array
5. Default initialization value of array element
6. Memory parsing of array
public class AarryTest { public static void main(String[] args) { //1. Declaration and initialization of one-dimensional array int num; //statement num = 10; //initialization int id = 100; //Declaration + initialization int[] ids; //statement //1.1 static initialization: the initialization of array and the assignment of array elements are carried out at the same time ids = new int[]{1001,1002,1003,1004}; //1.2 dynamic initialization: the initialization of array and the assignment of array elements are carried out separately String[] names = new String[5]; //Wrong writing int[] arr1 = new int[]; int[5] arr2 = new int[5]; int[] arr3 = new int[3] {1,2,3}; //Once the array is initialized, its length is determined } }
public class AarryTest { public static void main(String[] args) { String[] names = new String[5]; //2. How to call the element at the specified position of the array: call by index //The index of the array starts at 0 and ends at - 1 names[0] = "bastard"; names[1] = "WangTwo "; names[2] = "Wang San"; names[3] = "Wang Si"; names[4] = "Wang Wu"; //3. How to get the length of the array //Attribute: length System.out.println(names.length);//5 //4. How to traverse an array for(int i = 0; i < names.length; i++) { System.out.println(names[i]); } } }
Default initialization value of array elements
- Array element is integer: 0
- Array elements are floating point: 0.0
- Array elements are char type: 0 or '\ u0000', not '0'
- Array elements are boolean: false
- The array element is a reference data type: null (null value, meaning no assignment)
public class AarryTest { public static void main(String[] args) { //5. Default initialization value of array element int[] arr = new int[4]; for(int i = 0;i < arr.length;i++) { System.out.println(arr[i]); } System.out.println("***********"); short[] arr1 = new short[4]; for(int i = 0;i < arr1.length; i++) { System.out.println(arr1[i]); } System.out.println("***********"); float[] arr2 = new float[5]; for(int i = 0;i < arr2.length; i++) { System.out.println(arr2[i]); } System.out.println("***********"); char[] arr3 = new char[5]; for(int i = 0;i < arr3.length; i++) { System.out.println("----"+arr3[i]+"****"); } System.out.println("***********"); boolean[] arr4 = new boolean[5]; for(int i = 0;i < arr4.length; i++) { System.out.println(arr4[i]); } System.out.println("***********"); String[] arr5 = new String[5]; System.out.println(arr5[0]); } }
- Brief description of memory structure:
2. Exercise: use of one-dimensional array
1. Read the student's grades from the keyboard, find out the highest score, and output the student's grade.
Score > = highest score - 10, grade "A";
Score > = highest score - 20, grade "B";
Score > = highest score - 30, grade "C";
For the rest, the grade is "D".
import java.util.Scanner; public class AarryTest { public static void main(String[] args) { //1. Use Scanner to read the number of students Scanner scanner = new Scanner(System.in); System.out.println("Please enter the number of students:"); int number = scanner.nextInt(); //2. Create an array, store student scores and initialize dynamically int[] scores = new int[number]; //3. Assign values to the elements in the array int maxScore = 0; System.out.println("Please enter"+number+"Student scores:"); for(int i = 0; i < scores.length; i++) { scores[i] = scanner.nextInt(); //4. Get the maximum value of the elements in the array, that is, the highest score if(maxScore < scores[i]) { maxScore = scores[i]; } } //5. According to the difference between each student's score and the highest score, get the grade of each student, and output the grade and score char level; for(int i = 0; i < scores.length; i++) { if(maxScore - scores[i] <= 10) { level = 'A'; }else if(maxScore - scores[i] <= 20) { level = 'B'; }else if(maxScore - scores[i] <= 30) { level = 'C'; }else { level = 'D'; } System.out.println("student" + i + "score is" + scores[i] + ",grade is" + level); } } }
3. Use of multidimensional array
3.1 use of two-dimensional array
- understand:
For the understanding of two-dimensional array, we can see that one-dimensional array array1 exists as an element of another one-dimensional array array2 - Use of two-dimensional array:
1. Declaration and initialization of two-dimensional array
2. How to call the element at the specified position of the array
3. How to get the length of the array
4. How to traverse an array
5. Default initialization value of array element
6. Memory parsing of array
import java.util.Scanner; public class AarryTest { public static void main(String[] args) { //1. Declaration and initialization of two-dimensional array //initiate static int[][] arr1 = new int[][] {{1,2,3},{4,5},{7,8,9}}; //Dynamic initialization 1 String[][] arr2 = new String[3][2]; //Dynamic initialization 2 String[][] arr3 = new String[3][]; //2. How to call the element at the specified position of the array System.out.println(arr1[0][1]); //2 System.out.println(arr2[1][1]); //null arr3[1] = new String[4]; System.out.println(arr3[1][0]);//I don't quite understand why the output is null //3. How to get the length of the array System.out.println(arr1.length); //3 System.out.println(arr1[0].length); //3 System.out.println(arr1[1].length); //2 //4. How to traverse an array for(int i = 0; i < arr1.length; i++) { for(int j = 0; j < arr1[i].length; j++){ System.out.print(arr1[i][j] + " "); } System.out.println(); } } }
import java.util.Scanner; public class AarryTest { public static void main(String[] args) { int[][] arr = new int[4][3]; System.out.println(arr[0]);//[I@1c4af82c System.out.println(arr[0][0]);//0 System.out.println("**********"); float[][] arr1 = new float[4][3]; System.out.println(arr1[0]);//Address value[ F@123a439b System.out.println(arr1[0][0]);//0.0 System.out.println("**********"); String[][] arr2 = new String[4][2]; System.out.println(arr2[1]);//Address value [Ljava.lang.String;@53bd815b] System.out.println(arr2[1][1]);//null System.out.println("**********"); double[][] arr3 = new double[4][]; System.out.println(arr3[1]);//null System.out.println(arr3[1][0]);//report errors } }
3.2 practice of two-dimensional array
1. Print a 10 Line Yang Hui triangle using a two-dimensional array
Tips:
The first line has 1 element and the nth line has n elements
The first and last elements of each line are 1
Starting from the third line, for elements that are not the first element and the last element. Namely:
yanghui[i][j] = yanghui[i-1][j-1] + yanghui[i-1][j];
import java.util.Scanner; public class AarryTest { public static void main(String[] args) { //1. Declare and initialize a two-dimensional array int [][] yanghui =new int[10][];//Defines the number of rows in the array //2. Assign values to the elements of the array for(int i = 0; i < yanghui.length; i++) { yanghui[i] = new int[i+1];//Define the number of columns corresponding to each row of the array, that is, there are n columns in row n //2.1 assigning values to the first and last elements yanghui[i][0] = yanghui[i][i] = 1; //2.2 assign values to non first and last elements of each line for(int j = 1; j < yanghui[i].length-1; j++) { yanghui[i][j] = yanghui[i-1][j-1] + yanghui[i-1][j]; } } //3. Traverse two-dimensional array for(int i = 0; i < yanghui.length; i++) { for(int j = 0; j < yanghui[i].length; j++) { System.out.print(yanghui[i][j] + " "); } System.out.println(); } } }
2. Create an int array with a length of 6. The values of the array elements are required to be between 1-30 and assigned randomly. At the same time, the values of elements are required to be different
import java.util.Scanner; public class AarryTest { public static void main(String[] args) { //1. Declare and initialize a one-dimensional array int [] arr =new int[6]; //2. Assign values to the elements of the array: //2.1 assign a random number in [1,30] to the array by using the for loop for(int i = 0; i<arr.length; i++) { arr[i] = (int)(Math.random()*30 + 1); //2.2 after assigning the value to the first element, each element needs to be compared with each element in front of it to see whether it is equal. If it is found to be equal, it will jump out of the comparison cycle and re assign the value to the element for(int j = 0; j < i; j++) { if(arr[i] == arr[j]) { i--;//If this element is equal to any previous element, it will jump out of the loop and i minus 1. In this way, i plus 1 is equivalent to assigning a new value to this i ยท break; } } } //3. Traverse one-dimensional array for(int i = 0; i < arr.length; i++) { System.out.print(arr[i]+" "); } } }
3. Loop number
Type an integer [1,20] from the keyboard. Take this number as the size of the matrix and fill in the numbers of 1, 2, 3, 4... n*n in the form of clockwise spiral. For example: enter the number 2, then the program output: 1 2
***** ************************************************* ******************4 3
Method 1:
import java.util.Scanner; public class AarryTest { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter a 1~20 Integer of:"); int n = scanner.nextInt(); //1. Declare and initialize a two-dimensional array int [][] arr =new int[n][n]; int s = n*n; /* k=1:Right k=2: down k=3: left k=4: up */ //2. Assign values to the elements of the array: int k = 1; int i = 0, j = 0; for(int m = 1; m <= s; m++) { if(k==1){ if(j < n && arr[i][j]==0){ arr[i][j++] = m; }else { k = 2; i++; j--; m--; } }else if(k==2){ if(i < n && arr[i][j]==0){ arr[i++][j] = m; }else { k = 3; i--; j--; m--; } }else if(k==3){ if(j>=0 && arr[i][j]==0){ arr[i][j--] = m; }else { k = 4; i--; j++; m--; } }else if(k==4){ if(i>=0 && arr[i][j]==0){ arr[i--][j] = m; }else { k = 1; i++; j++; m--; } } } //3. Traverse two-dimensional array for(int x = 0; x < arr.length; x++) { for(int y = 0; y < arr[x].length; y++) { System.out.print(arr[x][y]+"\t"); } System.out.println(); } } }
Method 2:
import java.util.Scanner; public class AarryTest { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter a 1~20 Integer of:"); int n = scanner.nextInt(); int [][] arr = new int[n][n]; //1. Declare and initialize a two-dimensional array int count = 0;//Data to display int maxX = n-1;//x-axis maximum subscript int maxY = n-1;//y-axis maximum subscript int minX = 0;//x-axis minimum subscript int minY = 0;//y-axis minimum subscript while(minX <= maxX){ for(int x = minX; x <= maxX; x++){ arr[minY][x] = ++count; } minY++; for(int y = minY; y <= maxY; y++){ arr[y][maxX] = ++count; } maxX--; for(int x = maxX; x >= minX; x--){ arr[maxY][x] = ++count; } maxY--; for(int y = maxY; y >= minY; y--){ arr[y][minX] = ++count; } minX++; } //3. Traverse two-dimensional array for(int x = 0; x < arr.length; x++) { for(int y = 0; y < arr[x].length; y++) { System.out.print(arr[x][y]+"\t"); } System.out.println(); } } }
4. Average number in array elements, etc
Define a one-dimensional array of int type, including 10 elements, assign some random integers respectively, and then calculate the maximum, minimum and sum values of all elements. Requirement: all random numbers are two digits.
import javax.jws.soap.SOAPBinding; import java.util.Scanner; public class AarryTest { public static void main(String[] args) { int [] arr = new int[10]; for(int i = 0; i < arr.length; i++){ arr[i] = (int) (Math.random()*(99-10+1)+10); } //ergodic for(int i = 0; i < arr.length; i++){ System.out.print(arr[i] + "\t"); } System.out.println(); //Find the maximum value of array elements int maX = arr[0]; for(int i = 0; i < arr.length; i++){ if(arr[i] > maX){ maX = arr[i]; } } System.out.println("The maximum value is:"+maX); //Find the minimum value of array elements int miN = arr[0]; for(int i = 0; i < arr.length; i++){ if(arr[i] < miN){ miN = arr[i]; } } System.out.println("The minimum value is:"+miN); //Find the sum value of array elements int sum = 0; for(int i = 0; i < arr.length; i++){ sum += arr[i]; } System.out.println("The sum value is:"+sum); //Average array elements int avge = 0; avge = sum / arr.length; System.out.println("The average value is:"+avge); } }
5. Copy of array
Use simple arrays
(1) Create a class named ArrayTest and declare array1 and array2 variables in the main() method. They are arrays of type int [].
(2) Using braces {}, initialize array1 to 8 prime numbers: 2, 3, 5, 7, 9, 11, 13, 17, 19.
(3) Displays the contents of array1.
(4) Assign an array2 variable equal to array1, and modify the even index element in array2 to make it equal to the index value (for example, array[0]=0;array[2]=2). Print out array1.
import javax.jws.soap.SOAPBinding; import java.util.Scanner; public class AarryTest { public static void main(String[] args) { int[] array1,array2; array1 = new int[]{2,3,5,7,9,11,13,17,19}; //Display the contents of array1 for(int i = 0;i < array1.length; i++){ System.out.print(array1[i]+"\t"); } System.out.println(); //Assign the array2 variable equal to array1 array2 = array1;//It cannot be called a copy of an array //Copy of array array2 = new int[array1.length]; for(int i = 0;i < array2.length; i++){ array2[i] =array1[i]; } //Modify the even index element in array2 to make it equal to the index value (for example, array[0]=0;array[2]=2) for(int i = 0; i < array2.length; i++){ if(i%2 == 0){ array2[i] = i; } } //Print the contents of array1 for(int i = 0;i < array1.length; i++){ System.out.print(array1[i]+"\t"); } } }
The above example shows: "array2 = array1;" This operation only gives the address of array1 to array2, and does not copy array1. That is, the address values of the two variables are the same, but there is only one array in the heap space. In other words, from beginning to end, it is only new once. Array2 and array1 have the same address values, and both point to the only array entity in the heap space.
Copy heap interpretation of array:
Inverted array lookup and
import javax.jws.soap.SOAPBinding; import java.util.Scanner; public class AarryTest { public static void main(String[] args) { String[] arr = new String[]{"JJ","DD","MM","BB","GG","AA"}; //Copy of array (different from the assignment of array variable: arr1 = arr) String[] arr1 = new String[arr.length]; for(int i = 0; i < arr1.length; i++){ arr1[i] = arr[i]; } //Inversion of array //Method 1: for(int i = 0; i < arr.length/2; i++){ String temp = arr[i]; arr[i] = arr[arr.length-1-i]; arr[arr.length-1-i] = temp; } //Method 2: for(int i=0,j=arr.length-1; i < j; i++,j--){ String temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } //ergodic for(int i=0; i < arr.length; i++){ System.out.print(arr[i]+"\t"); } System.out.println(); //Find (search) //Linear search: String dest = "CB"; boolean ifFlag =true; for(int i = 0; i < arr.length;i++){ if(dest.equals(arr[i])){ System.out.println("The specified element was found at:"+i); ifFlag =false; break; } } if(ifFlag){ System.out.println("I'm sorry I didn't find it!"); } //Dichotomy search: the premise is that the array to be searched must be ordered int[] arr2 = new int[]{-98,-34,2,34,54,66,79,105,210,333}; int dest1 = -34; int head = 0;//Initial first index int end = arr2.length - 1;//Initial last index boolean ifFlag1 =true; while(head <= end){ int middle = (head+end)/2; if(dest1 == arr2[middle]){ System.out.println("The specified element was found at:"+middle); ifFlag1 =false; break; }else if(arr2[middle] > dest1){ end = middle-1; }else{//arr2[middle] < dest1 head = middle + 1; } } if(ifFlag1){ System.out.println("I'm sorry I didn't find it!"); } } }