An article solves the problems of adding, deleting, modifying and querying Java arrays (CRUD) (demonstration of knowledge points and exercises)!!!

Posted by DrJonesAC2 on Fri, 11 Feb 2022 06:13:33 +0100

1, What does array CURD mean

Array is a container for storing data. The method of operating data: CRUD -- add, delete, modify and query

C: Create data increase

R: Retrieve query data

U: Update modify data

D: Delete delete data

1. Add data: data can be added directly at the specified position through index / number / dry label

2. Query data: through index / number / subscript, you can directly query the data at the specified location

3. Modify data: through index / number / subscript, you can directly query the data at the specified location and replace the original data with new data

4. Delete data: deleting data is special. There are two methods: logical deletion and physical deletion

  • Logical deletion -- replace the data with null, and the simulation indicates that the data has been deleted (recommended)
  • Physical deletion -- [it is impossible to change the length of the array, and the location space of the specified deleted data cannot be modified]

Delete the data at the specified location, and reduce the data index of all subsequent locations by 1

  • Logical deletion: in java, null is used to represent null and nothing. For example: names[0] = null; Logically deleted data with index = 0
  • Physical deletion of data involves array migration.

Array migration

1, Add data to array:

Note: the array has the fixed length feature. Once the length is specified, it cannot be changed. Therefore, when adding data, judge whether to use array migration. If array migration is used, you need to create a new array and assign the value of the old array to the new array.

2, Array delete data:

Physical deletion: delete the data at the index position in the array [the index position will be deleted]

① The physical deletion mode in theory cannot be realized, and the array length cannot be changed!

② Delete the data at the index position, and all subsequent data indexes - 1

2, Exercises

1. Add data

1, Additional data that does not involve array migration

Exercise 1: the number of equipment that game characters can wear is 7. One initial character's equipment is {null, null, "Breaking Dawn", "electric knife", null, "breaking the army", "ordinary straw sandals"}, where null indicates that there is no equipment in this position. Now it is required to add 3 pieces of equipment to the game characters. The equipment name is input by the console and can only be equipped in the position where it is not worn. Finally, output all packages.

import java.util.Arrays;
import java.util.Scanner;

public class Player {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String[] array = {null, null, "dawn", "Electric knife", null, "Break the army", "Ordinary straw sandals"};
        /*
         * Idea:
         * 1,Loop through the array and find out that the position of the array is null
         * 2,If it is null, add a piece of equipment at this index position
         * 3,Finally, output the array after adding equipment
         */
        for (int i = 0; i < array.length; i++) {
            if (array[i] == null) {
                System.out.print("Please enter your number" + (i + 1) + "Pieces of equipment:");
                array[i] = input.next();
            }
        }
        System.out.println(Arrays.toString(array));
    }
}

Operation results:

2, Additional data involving array migration

 

Exercise 2: it is known that there are five students in the class group {"Xiaotian", "Zhang San", "Li Si", "Wang Wu", "Lao Liu"} whose seats are in the order of the table. Now a student "Xiaoling" has transferred to the class and assigned to the group, and assigned his seat behind Xiaotian and in front of Zhang San. Please output the seat table.

import java.util.Arrays;

public class Demo11 {
    public static void main(String[] args) {
        String[] array = {"Xiaotian", "Zhang San", "Li Si", "Wang Wu", "Old six"};
        String[] newArray = new String[array.length + 1];
        int index = 0;
//        1. Find the location of "Xiaotian"
        for (int i = 0; i < array.length; i++) {
            if (array[i].equals("Xiaotian")) {
                index = i;
            }
        }
//        2. Traverse the original array and assign the value of the original array to the new array
        for (int i = 0; i < array.length; i++) {
            newArray[i] = array[i];
        }
//        3. Starting from the index position, traverse the original array and move the data of the new array back in turn
        for (int i = array.length; i > index; i--) {
            newArray[i] = newArray[i - 1];
        }
//        index+1 is Xiaoling's seat. You need to assign a value to it, otherwise the seat will output index information
        newArray[index + 1] = "Xiao Ling";
        System.out.println(Arrays.toString(newArray));
    }
}

Operation results:

2. Query data

Idea: querying data generally involves traversing array queries, so loops and judgment statements will be used.

Exercise 1: known array: {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}. Write a program to guess numbers: enter a number and output whether the number exists in the array. If so, output its subscript position.

import java.util.Scanner;

public class Demo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter an integer:");
        int num = input.nextInt();
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
        int index = 0; //Index to check whether the input number exists in the array
        for (int i = 0; i < array.length; i++) {
            if (array[i] == num) {
                index = i;
            }
        }
        System.out.println("index=" + index);
    }
}

Operation results:

3. Modify data

Idea of modifying data: through index / number / subscript, you can directly query the data at the specified location and replace the original data with new data

Exercise 1: define an array of strings with a length of 5. Cycle through 5 names. Then input a user's name, check whether there is this person's name in the array, output the subscript, and then modify the name to a new name, which is input by the console, and finally print all names.

import java.util.Arrays;
import java.util.Scanner;

public class Example {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] array = new String[5];
        boolean flag = true;
        for (int i = 0; i < array.length; i++) {
            System.out.print("Please enter your name:");
            array[i] = scanner.next();
        }
        System.out.println("Array after input:" + Arrays.toString(array));
        System.out.print("Please enter the name to search:");
        String name = scanner.next();
        for (int i = 0; i < array.length; i++) {
            if (array[i].equals(name)) {
                flag = false;
                System.out.println("There's this man's name,Its array subscript is:"+i);
                System.out.print("Please enter a new name:");
                name = scanner.next();
                array[i] = name;
            }
        }
        if (flag) {
            System.out.println("There is no such name");
        }
        System.out.println("Array is:" + Arrays.toString(array));
    }
}

Operation results:

4. Delete data

To delete data, we need to understand a concept: once the length of the array is defined, it cannot be changed.

1, Delete data that does not involve array migration - logical deletion

Exercise 1: in the singing competition, a total of 10 judges will score. When calculating the singer's score, remove the highest score and the lowest score, and then average the scores of the remaining 8 judges, which is the final score of the player. Use the console to input the score of each judge, and finally calculate and output the score of the player.

import java.util.Arrays;

public class Test {
    public static void main(String[] args) {
        int[] array = {80, 190, 78, 90, 90, 99, 100, 80, 30, 88};
        int max = array[0];
        int min = array[0];
        int maxIndex = 0; //Maximum index
        int minIndex = 0; //Minimum index
        int sum = 0;
        int average;

//        Find the subscripts of the maximum and minimum values
        for (int i = 0; i < array.length; i++) {
            if (max < array[i]) {
                max = array[i];
                maxIndex = i;
            }
            if (min > array[i]) {
                min = array[i];
                minIndex = i;
            }
        }

//        "Delete" the maximum and minimum values
        for (int i = 0; i < array.length; i++) {
            if (i == maxIndex || i == minIndex) {
                array[i] = 0; //Because the array is an integer, assign it 0 instead of null
            } else {
                sum += array[i];
            }
        }
//        Output array, average score
        average = sum / (array.length - 2);
        System.out.println(Arrays.toString(array));
        System.out.println("average average=" + average);
    }
}

Operation results:

2, Delete data involving array migration - Physical deletion

Idea: find the position where the element needs to be deleted, and then move the array forward from this position.

Exercise 2: there is an array {"Tom", "Jack", "Mary", "Jason"}. Find the jack in the array and delete it. Finally, output the deleted array.

Code implementation:

import java.util.Arrays;
import java.util.Scanner;

public class Demo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String[] array = {"Tom", "Jack", "Marry", "Jison"};
        String[] newArray = new String[array.length - 1];
        System.out.println("Original array=" + Arrays.toString(array));
        System.out.print("Please enter the name you want to delete:");
        String name = input.next();
        int index = 0;
//        Find out where Jack is in the array
        for (int i = 0; i < array.length; i++) {
            if (name.equals(array[i])) {
                index = i;
            }
        }
//        Starting from the Jack position, move the following array elements forward one bit
        for (int i = index; i < array.length - 1; i++) {
            array[i] = array[i + 1];
        }
//        Assign the deleted array to the new array
        for (int i = 0; i < newArray.length; i++) {
            newArray[i] = array[i];
        }
        System.out.println(Arrays.toString(newArray));
    }
}

Operation results:

Exercise 3: in the singing competition, a total of 10 judges will score. The score array is {80, 190, 78, 90, 90, 99, 100, 80, 30, 88}. Remove the highest score and the lowest score, and then the remaining 8-digit scores will be output in the form of array.

Idea: find out the coordinates of the most value, then migrate the array, and finally assign a value to the new array output.

Code implementation:

import java.util.Arrays;

public class Demo {
    public static void main(String[] args) {
        int[] array = new int[]{80, 190, 78, 90, 90, 99, 100, 80, 30, 88};
        int[] newArray = new int[array.length - 2];
        int max = array[0];
        int min = array[0];
        int maxIndex = 0;
        int minIndex = 0;
        System.out.println("The initial array is:" + Arrays.toString(array));

//        Find the subscripts of the maximum and minimum values
        for (int i = 0; i < array.length; i++) {
            if (max < array[i]) {
                max = array[i];
                maxIndex = i;
            }
            if (min > array[i]) {
                min = array[i];
                minIndex = i;
            }
        }

//        Delete maximum and minimum values
        for (int i = maxIndex; i < array.length - 1; i++) {
            for (int j = minIndex; j <= array.length - 2; j++) {
                array[j] = array[j + 1];
            }
            array[i] = array[i + 1];
        }
//        Assign the deleted array to the new array
        for (int i = 0; i < newArray.length; i++) {
            newArray[i] = array[i];
        }
        System.out.println("The array with the most value removed is:" + Arrays.toString(newArray));
    }
}

Operation results:

The writing is not very good. I hope you guys will forgive me.

 

 

Topics: Java array