Java learning notes 09: Java_ArrayList_ Student management system

Posted by kanika on Wed, 29 Dec 2021 12:56:21 +0100

1.ArrayList

Differences between sets and arrays:

Common ground: they are containers for storing data

Difference: the capacity of the array is fixed and the capacity of the collection is variable

1.1 - construction method and addition method of ArrayList

public ArrayList()Create an empty collection object
public boolean add(E e)Appends the specified element to the end of this collection
public void add(int index,E element)Inserts the specified element at the specified location in this collection

ArrayList :

Resizable array implementation

: is a special data type, generic.

How?

Where E appears, we can replace it with the reference data type

Example: ArrayList, ArrayList

1.2 common methods of ArrayList [application]

**Member method:**

public boolean remove(Object o)Delete the specified element and return whether the deletion is successful
public E remove(int index)Deletes the element at the specified index and returns the deleted element
public E set(int index,E element)Modify the element at the specified index and return the modified element
public E get(int index)Returns the element at the specified index
public int size()Returns the number of elements in the collection

Example code:

public class ArrayListDemo02 {
    public static void main(String[] args) {
        //Create collection
        ArrayList<String> array = new ArrayList<String>();

        //Add element
        array.add("hello");
        array.add("world");
        array.add("java");

        //public boolean remove(Object o): deletes the specified element and returns whether the deletion was successful
//        System.out.println(array.remove("world"));
//        System.out.println(array.remove("javaee"));

        //public E remove(int index): deletes the element at the specified index and returns the deleted element
//        System.out.println(array.remove(1));

        //IndexOutOfBoundsException
//        System.out.println(array.remove(3));

        //public E set(int index,E element): modifies the element at the specified index and returns the modified element
//        System.out.println(array.set(1,"javaee"));

        //IndexOutOfBoundsException
//        System.out.println(array.set(3,"javaee"));

        //public E get(int index): returns the element at the specified index
//        System.out.println(array.get(0));
//        System.out.println(array.get(1));
//        System.out.println(array.get(2));
        //System.out.println(array.get(3)); //??????  Self test

        //public int size(): returns the number of elements in the collection
        System.out.println(array.size());

        //Output set
        System.out.println("array:" + array);
    }
}

1.3 ArrayList stores strings and traverses

Case requirements:

Create a collection of stored strings, store 3 string elements, and use the program to traverse the collection on the console

Implementation steps:

1:Create collection object
    2:Adds a string object to the collection
    3:To traverse a collection, you must first be able to get each element in the collection get(int index)Method implementation
    4:Traverse the set, and then you should be able to get the length of the set size()Method implementation
    5:General format for traversing collections

Code implementation:

/*
    Idea:
        1:Create collection object
        2:Adds a string object to the collection
        3:To traverse the collection, you must first be able to get each element in the collection, which is implemented through the get(int index) method
        4:After traversing the set, you should be able to obtain the length of the set, which is realized through the size() method
        5:General format for traversing collections
 */
public class ArrayListTest01 {
    public static void main(String[] args) {
        //Create collection object
        ArrayList<String> array = new ArrayList<String>();

        //Adds a string object to the collection
        array.add("Liu Zhengfeng");
        array.add("Zuo lengchan");
        array.add("Breezy");

        //After traversing the set, you should be able to obtain the length of the set, which is realized through the size() method
//        System.out.println(array.size());

        //General format for traversing collections
        for(int i=0; i<array.size(); i++) {
            String s = array.get(i);
            System.out.println(s);
        }
    }
}

1.4 ArrayList stores student objects and traverses them

Case requirements:

Create a collection of student objects, store 3 student objects, and use the program to traverse the collection on the console

**Implementation steps:**

1: define student class

2: create collection object

3: create student object

4: add student object to collection

5: traversal set, implemented in general traversal format

Code implementation:

/*
    Idea:
        1:Define student classes
        2:Create collection object
        3:Create student object
        4:Add student object to collection
        5:Traversal set, using the general traversal format
 */
public class ArrayListTest02 {
    public static void main(String[] args) {
        //Create collection object
        ArrayList<Student> array = new ArrayList<>();

        //Create student object
        Student s1 = new Student("Lin Qingxia", 30);
        Student s2 = new Student("Breezy", 33);
        Student s3 = new Student("Zhang Manyu", 18);

        //Add student object to collection
        array.add(s1);
        array.add(s2);
        array.add(s3);

        //Traversal set, using the general traversal format
        for (int i = 0; i < array.size(); i++) {
            Student s = array.get(i);
            System.out.println(s.getName() + "," + s.getAge());
        }
    }
}

1.5 enter student information into the collection with the keyboard

Case requirements:

Create a collection of student objects, store 3 student objects, and use the program to traverse the collection on the console

The student's name and age are entered from the keyboard

Implementation steps:

1: define the student class. For the convenience of keyboard data entry, all member variables in the student class are defined as String type

2: create collection object

3: enter the data required by the student object with the keyboard

4: create a student object and assign the data entered on the keyboard to the member variable of the student object

5: add student object to collection

6: traversal set, implemented in general traversal format

Code implementation:

/*
    Idea:
        1:Define the student class. For the convenience of keyboard data entry, all member variables in the student class are defined as String type
        2:Create collection object
        3:Enter the data required by the student object with the keyboard
        4:Create a student object and assign the data entered by the keyboard to the member variable of the student object
        5:Add a student object to the collection
        6:Traversal set, using the general traversal format
 */
public class ArrayListTest {
    public static void main(String[] args) {
        //Create collection object
        ArrayList<Student> array = new ArrayList<Student>();

        //In order to improve the reusability of code, we use methods to improve the program
        addStudent(array);
        addStudent(array);
        addStudent(array);

        //Traversal set, using the general traversal format
        for (int i = 0; i < array.size(); i++) {
            Student s = array.get(i);
            System.out.println(s.getName() + "," + s.getAge());
        }
    }

    /*
        Two clear:
            Return value type: void
            Parameters: ArrayList < student > array
     */
    public static void addStudent(ArrayList<Student> array) {
        //Enter the data required by the student object with the keyboard
        Scanner sc = new Scanner(System.in);

        System.out.println("Please enter student name:");
        String name = sc.nextLine();

        System.out.println("Please enter student age:");
        String age = sc.nextLine();

        //Create a student object and assign the data entered by the keyboard to the member variable of the student object
        Student s = new Student();
        s.setName(name);
        s.setAge(age);

        //Add a student object to the collection
        array.add(s);
    }
}

2. Student management system

2.1 implementation steps of student management system

  • Case requirements

    According to what we have learned at present, complete a comprehensive case: student management system! The main functions of the system are as follows:

    Add student: enter student information through the keyboard and add it to the collection

    Delete student: enter the student number of the student to be deleted through the keyboard to delete the student object from the set

    Modify student: enter the student number of the student to be modified through the keyboard to modify other information of the student object

    View student: display the student object information in the collection

    Exit the system: end the program

  • Implementation steps

    1. Define a student class that contains the following member variables

      Student class: student member variable:

      Student No.: sid

      Name: name

      Age: age

      Birthday: birthday

      Construction method:

      Nonparametric structure

      Construction member method with four parameters:

      Each member variable is given a get/set method

    2. Steps to build the main interface of student management system

      2.1 write the main interface with output statements

      2.2 using Scanner to enter data with keyboard

      2.3 select operation with switch statement

      2.4 complete the cycle and return to the main interface again

    3. Implementation steps of adding student functions to student management system

      3.1 enter and select add students with the keyboard

      3.2 define a method for adding students

      A prompt message is displayed to prompt what information to enter

      Enter the data required by the student object with the keyboard

      Create a student object and assign the data entered by the keyboard to the member variable of the student object

      Add student object to collection (save)

      Give a prompt of successful addition

      3.3 calling method

    4. Implementation steps of viewing student function in student management system

      4.1 input, select and view all student information with the keyboard

      4.2 define a method for viewing student information

      Display header information

      Take out the data in the set, display the student information according to the corresponding format, and display the supplementary "age" for the age

      4.3 calling method

    5. Implementation steps of deleting student function in student management system

      5.1 enter and delete student information with the keyboard

      5.2 define a method to delete student information

      Display prompt information

      Enter the student number to be deleted

      Call the getIndex method to find the index of the student number in the collection

      If the index is - 1, the prompt message does not exist

      If the index is not - 1, call the remove method to delete and prompt that the deletion is successful

      5.3 calling method

    6. Modification of student management system and implementation steps of student function

      6.1 enter, select and modify student information with the keyboard

      6.2 define a method for modifying student information

      Display prompt information

      Enter the student number to be modified on the keyboard

      Call the getIndex method to find the index of the student number in the collection

      If the index is - 1, the prompt message does not exist

      If the index is not - 1, enter the student information to be modified with the keyboard

      Set to modify the corresponding student information

      Prompt for successful modification

      6.3 calling method

    7. Exit the system

      Use system exit(0); Exit JVM

2.2 definition of students

package com.itheima.domain;

public class Student {
    private String sid; // Student number
    private String name; // full name
    private int age; // Age
    private String birthday; // birthday

    public Student() {
    }

    public Student(String sid, String name, int age, String birthday) {
        this.sid = sid;
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    public String getSid() {
        return sid;
    }

    public void setSid(String sid) {
        this.sid = sid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }
}

2.3 definition of test class

package com.itheima.test;

import com.itheima.domain.Student;

import java.util.ArrayList;
import java.util.Scanner;

public class StudentManager {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        // Create collection container object
        ArrayList<Student> list = new ArrayList<>();

        lo:
        while (true) {
            // 1. Set up main interface menu
            System.out.println("--------Welcome to the student management system--------");
            System.out.println("1 Add student");
            System.out.println("2 Delete student");
            System.out.println("3 Modify student");
            System.out.println("4 View students");
            System.out.println("5 sign out");
            System.out.println("Please enter your choice:");

            String choice = sc.next();

            switch (choice) {
                case "1":
                    //System.out.println("add student");
                    addStudent(list);
                    break;
                case "2":
                    //System.out.println("delete student");
                    deleteStudent(list);
                    break;
                case "3":
                    //System.out.println("modify student");
                    updateStudent(list);
                    break;
                case "4":
                    // System.out.println("view students");
                    queryStudents(list);
                    break;
                case "5":
                    System.out.println("Thank you for your use");
                    break lo;
                default:
                    System.out.println("Your input is incorrect");
                    break;
            }
        }


    }

    // Modify student's method
    public static void updateStudent(ArrayList<Student> list) {
        System.out.println("Please enter the student number you want to modify:");
        Scanner sc = new Scanner(System.in);
        String updateSid = sc.next();
        // 3. Call getIndex method to find the index position of the student number in the collection
        int index = getIndex(list,updateSid);
        // 4. Judge whether the student number exists in the set according to the index
        if(index == -1){
            // Does not exist: prompt
            System.out.println("No information found, Please re-enter");
        }else{
            // Presence: receive new student information
            System.out.println("Please enter a new student name:");
            String name = sc.next();
            System.out.println("Please enter a new student age:");
            int age = sc.nextInt();
            System.out.println("Please enter a new student birthday:");
            String birthday = sc.next();
            // Encapsulate as a new student object
            Student stu = new Student(updateSid, name, age, birthday);
            // Call the set method of the collection to complete the modification
            list.set(index, stu);
            System.out.println("Modified successfully!");
        }
    }

    // How to delete students
    public static void deleteStudent(ArrayList<Student> list) {
        // 1. Give prompt information (please enter the student number you want to delete)
        System.out.println("Please enter the student ID you want to delete:");
        // 2. The keyboard receives the student number to be deleted
        Scanner sc = new Scanner(System.in);
        String deleteSid = sc.next();
        // 3. Call getIndex method to find the index position of the student number in the collection
        int index = getIndex(list,deleteSid);
        // 4. Judge whether the student number exists in the set according to the index
        if(index == -1){
            // Does not exist: prompt
            System.out.println("No information found, Please re-enter");
        }else{
            // Existing: delete
            list.remove(index);
            System.out.println("Delete succeeded!");
        }
    }

    // How to view students
    public static void queryStudents(ArrayList<Student> list) {
        // 1. Judge whether there is data in the set. If there is no data, give a prompt directly
        if(list.size() == 0){
            System.out.println("no message, Please add and query again");
            return;
        }
        // 2. Exist: displays header data
        System.out.println("Student number\t\t full name\t Age\t birthday");
        // 3. Traverse the collection, get the information of each student object, and print it on the console
        for (int i = 0; i < list.size(); i++) {
            Student stu = list.get(i);
            System.out.println(stu.getSid() + "\t" + stu.getName() + "\t" + stu.getAge() + "\t\t" + stu.getBirthday());
        }
    }

    // How to add students
    public static void addStudent(ArrayList<Student> list) {
        Scanner sc = new Scanner(System.in);
        // 1. Give the input prompt information

        String sid;

        while(true){
            System.out.println("Please enter student number:");
            sid = sc.next();

            int index = getIndex(list, sid);

            if(index == -1){
                // sid does not exist, student ID can be used
                break;
            }
        }

        System.out.println("Please enter your name:");
        String name = sc.next();
        System.out.println("Please enter age:");
        int age = sc.nextInt();
        System.out.println("Please enter birthday:");
        String birthday = sc.next();
        // 2. Encapsulate the information entered by the keyboard as a student object
        Student stu = new Student(sid,name,age,birthday);
        // 3. Add the encapsulated Student object to the collection container
        list.add(stu);
        // 4. Give the prompt of successful addition
        System.out.println("Added successfully!");
    }

    /*
        getIndex : Receive a collection object and a student number

        Find the index position of this student number in the collection
     */
    public static int getIndex(ArrayList<Student> list, String sid){
        // 1. Assume that the incoming student number does not exist in the collection
        int index = -1;
        // 2. Traverse the collection, get each student object, and prepare to find it
        for (int i = 0; i < list.size(); i++) {
            Student stu = list.get(i);
            // 3. Obtain the student number of each student object
            String id = stu.getSid();
            // 4. Compare the retrieved student number with the incoming student number (the searched student number)
            if(id.equals(sid)){
                // Exist: let the index variable record the correct index position
                index = i;
            }
        }

        return index;
    }
}

😉😉😉

print("If the article is useful to you, please like it O(∩_∩)O~")
System.out.println("If the article is useful to you, please like it O(∩_∩)O~");
cout<<"If the article is useful to you, please like it O(∩_∩)O~"<<endl;

😉😉😉

Topics: Java