[Yugong series] December 2021 Java Teaching Course 18 - array

Posted by NightFalcon90909 on Tue, 04 Jan 2022 19:01:24 +0100

1, Array

1.1 array introduction

An array is a container for storing data with a fixed length. The data types for storing multiple data should be consistent.

1.2 definition format of array

1.2. 1 first format

Data type [] array name

Example:

int[] arr;        
double[] arr;      
char[] arr;

1.2. 2 second format

Data type array name []

Example:

int arr[];
double arr[];
char arr[];

1.3 dynamic initialization of array

1.3. 1 what is dynamic initialization

Array dynamic initialization is to give only the length of the array and the default initialization value is given by the system

1.3. 2 dynamic initialization format

data type[] Array name = new data type[Array length];
int[] arr = new int[3];

1.3. 3 detailed explanation of dynamic initialization format

  • To the left of the equal sign:

    • int: data type of array

    • []: represents that this is an array

    • arr: represents the name of the array

  • To the right of the equal sign:

    • new: open up memory space for arrays
    • int: data type of array
    • []: represents that this is an array
    • 5: Represents the length of the array

code:

package com.itheima.array;

public class Demo2Array {
    /*
        Dynamic initialization of array:
                        During initialization, you need to manually specify the length of the array, and the system will allocate the initial value to the array container

        Dynamic initialization format:
                        Data type [] array name = new data type [length of array];

        be careful:
                        When printing array variables, the memory address of the array will be printed

        [I@10f87f48 :

                        @ : Separator
                        [ : The current space is an array type
                        I : The data type stored in the current array container
                        10f87f48 : Hexadecimal memory address

                                0 1 2 3 4 5 6 7 8 9 a b c d e f
     */
    public static void main(String[] args) {
        // Data type [] array name = new data type [length of array];
        // An array container of int type is created through the new keyword. The container can store five integers of int type. The container is recorded by the arr array variable
        int[] arr = new int[5];
        // [I@10f87f48
        System.out.println(arr);

        byte[] bArr = new byte[3];
        // [B@b4c966a
        System.out.println(bArr);

    }
}

1.4 array element access

1.4. 1 what is an index

Each element stored in the array will automatically have a number, starting from 0.

This automatic numbering is called array index, and the elements in the array can be accessed through the index of the array.

1.4. 2 access array element format

Array name[Indexes];

1.4. 3 example code

package com.itheima.array;

public class Demo3ArrayIndex {
    /*
        Array dynamic initialization:
                When initializing, manually specify the array length, and the system will allocate the initial value to the array container

        Element access format of array:
                Array name [index]

                Index: the numbering method of data in the array, starting from 0
                Function: access the spatial location in the array container

        be careful:
                After the array is created, it can be taken out even without assignment, but the elements taken out are the default initialization values

     */
    public static void main(String[] args) {
        int[] arr = new int[3];         // 0 1 2
        System.out.println(arr);        // Memory address of array[ I@10f87f48

        // Array name [index] accesses the spatial location in the array container
        System.out.println(arr[0]);     // 0 is the default initialization value automatically assigned by the system
        System.out.println(arr[1]);
        System.out.println(arr[2]);

        System.out.println("--------------");

        // Array name [index]
        arr[0] = 11;
        arr[1] = 22;
        arr[2] = 33;

        System.out.println(arr[0]);
        System.out.println(arr[1]);
        System.out.println(arr[2]);
    }
}

1.5 memory allocation

1.5. 1 memory overview

Memory is an important original and temporary storage area in the computer. It is used to run programs.

The program we write is stored in the hard disk, and the program in the hard disk will not run.

It must be put into memory to run. After running, the memory will be emptied.

In order to run programs, Java virtual machine must allocate and manage memory space.

1.5. 2 memory allocation in Java

  • At present, we only need to remember two memories: stack memory and heap memory
Area nameeffect
registerIt has nothing to do with our development.
Native Method Stack JVM is used when using operating system functions, which has nothing to do with our development.
Method areaStore class files that can be run.
Heap memoryStorage objects or arrays, created by new, are stored in heap memory.
Method stackThe memory used when the method runs, such as the main method, enters the method stack for execution.

1.6 Java memory allocation - an array memory diagram

1.7 memory diagram of two arrays

1.8 multiple arrays point to the same memory map

1.9 static initialization of array

1.9. 1 what is static initialization

When creating an array, the elements are directly determined

1.9. 2 static initialization format

  • Full version format

    data type[] Array name = new data type[]{Element 1,Element 2,...};
    
  • Simplified format

    data type[] Array name = {Element 1,Element 2,...};
    

1.9. 3 example code

package com.itheima.array2;

public class Demo1Array {
    /*
        Array static initialization: specify the initial value of each array element during initialization, and the array length is determined by the system

        Full format:
                    Data type [] array name = new data type [] {data 1, data 2, data 3...};
        Simplified format:
                    Data type [] array name = {data 1, data 2, data 3...};
     */
    public static void main(String[] args) {
        // Data type [] array name = new data type [] {data 1, data 2, data 3...};
        int[] arr = new int[]{11,22,33};
        System.out.println(arr[0]);
        System.out.println(arr[1]);
        System.out.println(arr[2]);

        // Data type [] array name = {data 1, data 2, data 3...};
        int[] arr2 = {44,55,66};
        System.out.println(arr2);
        System.out.println(arr2[0]);
        System.out.println(arr2[1]);
        System.out.println(arr2[2]);

    }
}

1.10 two common problems of array operation

1.10. 1 index out of bounds exception

  • Cause of occurrence

    public class ArrayDemo {
        public static void main(String[] args) {
            int[] arr = new int[3];
            System.out.println(arr[3]);
        }
    }
    

    The array length is 3 and the index range is 0 ~ 2, but we accessed an index of 3.

    After the program runs, an array out of bounds exception of ArrayIndexOutOfBoundsException will be thrown. In the development, the out of bounds exception of the array cannot occur. Once it occurs, we must modify the code we write.

  • Solution

    Modify the wrong index to the correct index range!

1.10. 2 null pointer exception

  • Cause of occurrence

    public class ArrayDemo {
        public static void main(String[] args) {
            int[] arr = new int[3];
    
            //Assign null to array
            arr = null;
            System.out.println(arr[0]);
        }
    }
    

    The line of code arr = null means that the variable arr will not save the memory address of the array, so it is not allowed to operate the array. Therefore, a null pointerexception null pointer exception will be thrown during operation. In development, null pointer exceptions cannot occur. Once they occur, we must modify the code we write.

  • Solution

    Give the array a real heap memory space reference!

1.11 array traversal

  • Array traversal: it is to get each element in the array separately, which is traversal. Traversal is also the cornerstone of array operations.

    public class ArrayTest01 {
    	public static void main(String[] args) {
    		int[] arr = { 1, 2, 3, 4, 5 };
    		System.out.println(arr[0]);
    		System.out.println(arr[1]);
    		System.out.println(arr[2]);
    		System.out.println(arr[3]);
    		System.out.println(arr[4]);
    	}
    }
    

    The above code can traverse all the elements in the array, but if there are many array elements, this writing method will certainly not work, so we need to transform it into a circular writing method. The index of the array is 0 to lenght-1, which can appear as a condition of the loop.

    public class ArrayTest01 {
        public static void main(String[] args) {
            //Define array
            int[] arr = {11, 22, 33, 44, 55};
    
            //Use a common traversal format
            for(int x=0; x<arr.length; x++) {
                System.out.println(arr[x]);
            }
        }
    }
    

1.12 get maximum value from array

  • Get maximum value: find the maximum value from all elements of the array.

  • Implementation idea:

    • Define variables to hold the elements on the index of array 0
    • Traverse the array to get each element in the array
    • Compare the traversed element with the variable that holds the value on the index of array 0
    • If the value of the array element is greater than the value of the variable, the variable records the new value
    • After the array loop is traversed, the variable saves the maximum value in the array
  • Code implementation:

    package com.itheima.test;
    
    import java.util.Scanner;
    
    public class Test2Array {
        /*
            Requirement: find maximum value from array
    
                    int[] arr = {12,45,98,73,60};
    
            Implementation steps:
                    1. Assume that the first element in the array is the maximum value
                    2. Traverse the array, get each element, and prepare for comparison
                    3. If there is a larger value than max during the comparison, let Max record a larger value
                    4. At the end of the cycle, print the maximum value
         */
        public static void main(String[] args) {
            int[] arr = {12,45,98,73,60};
            // 1. Assume that the first element in the array is the maximum value
            int max = arr[0];
            // 2. Traverse the array, get each element, and prepare for comparison
            for(int i = 1; i < arr.length; i++){
                // 3. If there is a larger value than max during the comparison, let Max record a larger value
                if(arr[i] > max){
                    max = arr[i];
                }
            }
            //  4. After the cycle ends, print the maximum value
            System.out.println("max:" + max);
        }
    }
    
    

1.13 summation of array elements

  • Requirements: enter 5 integers on the keyboard, store them in the array, and sum the array

  • Idea:
    1. Create a keyboard entry object and prepare for keyboard entry
    2. Define a summation variable and prepare to record the accumulated result
    3. Dynamically initialize an int array with a length of 5 to store the value entered by the keyboard
    4. Store the value entered by the keyboard into the array
    5. Traverse the array, take out each element, and sum
    6. Total output

  • Code implementation:

    package com.itheima.test;
    
    import java.util.Scanner;
    
    public class Test3Array {
        /*
            Requirements: enter 5 integers on the keyboard, store them in the array, and sum the array
    
            Idea:
                1.Create a keyboard entry object and prepare for keyboard entry
                2.Define a summation variable and prepare to record the accumulated result
                3.Dynamically initialize an int array with a length of 5 to store the value entered by the keyboard
                4.Store the value entered by the keyboard into the array
                5.Traverse the array, take out each element, and sum
                6.Output sum
         */
        public static void main(String[] args) {
            // 1. Create a keyboard entry object and prepare for keyboard entry
            Scanner sc = new Scanner(System.in);
            // 2. Define a summation variable and prepare to record the accumulated result
            int sum = 0;
            // 3. Dynamically initialize an int array with a length of 5 to store the value entered by the keyboard
            int[] arr = new int[5];
            // 4. Store the value entered by the keyboard into the array
            for(int i = 0; i < arr.length; i++){
                System.out.println("Please enter page" + (i+1) + "Integer:");
                //arr[i] = 10;
                arr[i] = sc.nextInt();
            }
    
            // 5. Traverse the array, take out each element, and sum
            for (int i = 0; i < arr.length; i++) {
                sum += arr[i];
            }
    
            // 6. Total output
            System.out.println("sum:" + sum);
    
        }
    }
    
    

1.14 basic array search [ application ]

  • Requirements:
    An array arr = {19, 28, 37, 46, 50} is known; Enter a data with the keyboard, find the index of the data in the array, and control
    Index value found for the pallet output.

  • Idea:
    1. Define an array and use static initialization to complete the initialization of array elements
    2. Enter the data to be searched with the keyboard and receive it with a variable
    3. Define an index variable with an initial value of - 1
    4. Traverse the array and get each element in the array
    5. Compare the data entered on the keyboard with each element in the array. If the values are the same, assign the index corresponding to the value to the index variable and end the cycle
    6. Output index variable

  • Code implementation:

    public static void main(String[] args) {
            // 1. Define an array and use static initialization to complete the initialization of array elements
            int[] arr = {19, 28, 37, 46, 50};
            // 2. Enter the data to be searched with the keyboard and receive it with a variable
            Scanner sc = new Scanner(System.in);
            System.out.println("Please enter the element you want to find:");
            int num = sc.nextInt();
            // 3. Define an index variable with an initial value of - 1
            // Suppose that the data to be searched does not exist in the array
            int index = -1;
            // 4. Traverse the array and get each element in the array
            for (int i = 0; i < arr.length; i++) {
                // 5. Compare the data entered on the keyboard with each element in the array. If the values are the same, assign the index corresponding to the value to the index variable and end the cycle
                if(num == arr[i]){
                    // If the values are the same, assign the index corresponding to the value to the index variable and end the loop
                    index = i;
                    break;
                }
            }
            //  6. Output index variable
            System.out.println(index);
        }
    }
    
    

1.15 scoring by judges [ application ]

  • Requirements: in the programming competition, 6 judges score the contestants, with an integer score of 0-100.
    The final score of the contestant is the average value of the four judges after removing the highest score and the lowest score (regardless of the decimal part).

  • Idea:
    1. Define an array and complete the initialization of array elements with dynamic initialization. The length is 6
    2. Enter the judges' scores on the keyboard
    3. Since there are 6 judges scoring, the operation of receiving judges' scores is carried out in cycle
    4. Find the maximum value of the array
    5. Find the minimum value of the array
    6. Sum the array
    7. Calculate according to the calculation rules to get the average score
    8. Average output score

  • Code implementation:

        public static void main(String[] args) {
            // 1. Define an array and complete the initialization of array elements with dynamic initialization. The length is 6
            int[] arr = new int[6];
            // 2. Enter the judges' scores on the keyboard
            Scanner sc = new Scanner(System.in);
            //  3. Since there are 6 judges scoring, the operation of receiving judges' scores is carried out in cycle
            for (int i = 0; i < arr.length; i++) {
                System.out.println("Please enter page" + (i+1) + "Scoring of judges:");
                int score = sc.nextInt();
                if(score >= 0 && score <= 100){
                    // Legal score
                    arr[i] = score;
                }else{
                    // Illegal score
                    System.out.println("Your scoring input is incorrect, Please check if it is 0-100 Between");
                    i--;
                }
            }
    
            // 4. Find the maximum value of the array
            int max = arr[0];
            for (int i = 1; i < arr.length; i++) {
                if(max < arr[i]){
                    max = arr[i];
                }
            }
    
            // 5. Find the minimum value of the array
            int min = arr[0];
            for (int i = 1; i < arr.length; i++) {
                if(min > arr[i]){
                    min = arr[i];
                }
            }
    
            // 6. Sum the array
            int sum = 0;
            for (int i = 0; i < arr.length; i++) {
                sum += arr[i];
            }
    
            // 7. Calculate according to the calculation rules to get the average score
            int avg = (sum - max - min ) / 4;
    
            // 8. Average output score
            System.out.println(avg);
        }
    }
    

Topics: Java Back-end