Detailed explanation of "set and generics" in Java hard core programming experiment [full details & complete source code]

❥ as a supplement to the "detailed explanation of Java hard core programming experiment" series in school year ❥

catalogue

☀️| I. experimental purpose

☀️| II. Experimental contents

❀1. Topic: writing programs to practice the basic use of generics and List collections

❀2. Topic: writing programs to practice the basic use of generics and Map collections

❀3. Title: design a Book shopping cart based on the idea of the textbook [case 7-8]

❀4. Title: complete the following practical projects under Eclipse (optional)

☀️| III. experimental results

⭐ 1. Source code:

⭐ ⒋ 2. Source code:

⭐ ⒋ 3. Source code:

⭐ ⅸ 4. Architecture & source code:

☀️| I. experimental purpose

1. Understand the concept, architecture, classification and usage scenarios of collections

2. Master Set interface and main implementation classes

3. Master List interface and main implementation classes

4. Master Map interface and main implementation classes

5. Understand the role of generics and master the application of type safety check in collections

☀️| II. Experimental contents

❀ 1. Topic: write a program to practice the basic use of generic and List sets

(1) Create an ArrayList collection that can only hold String objects named strNames;

(2) Add 5 string objects to the set in order: "School of information and Telecommunications", "School of mathematics and physics", "School of electromechanical", "School of civil engineering" and "School of food";

(3) Traverse the set (master several methods of traversing the set), and print the position and content of each element in the set respectively;

(4) First print the size of the set, then delete the third element in the set and display the content of the deleted element, then print the content of the third element in the current set, and print the size of the set again.

(5) The name of the test program is SY6_1_List, and the package name is com.xzit.sy6

☞ thinking:

If you replace the ArrayList set in (1) with the HashSet set set, what is the difference in the program? Programming test.

Experimental results:

If it is replaced with Hashset, it cannot be traversed by ordinary for loop

❀ 2. Topic: writing programs to practice the basic use of generics and Map sets

(1) Create a Book class, which contains the ISBN number, book name, author, publisher, publication date, book price and other attributes of the book.

(2) Create a booksmap object of map < Key, Values > type, where the Key type is the ISBN number of the Book and the Values type is the Book object.

(3) Add five "key value" objects to the booksmap set, that is, five ISBN numbers correspond to five book information.

(4) Traverse the set and print the value of each element in the set respectively;

(5) First print the size of the collection, then delete the book element containing java in the book name in the collection, display the content of the deleted element, and print the size of the collection again.

(6) The name of the test program is SY6_2_Map, and the package name is com.xzit.sy6

Experimental results:

❀ 3. Title: design a Book shopping cart based on the ideas of the textbook [case 7-8]

Store the information of books purchased by users. Be able to print out the information of books in the shopping cart, book price, subtotal and total cost. Simulate the shopping cart with HashMap class.

Implementation guidance:

(1) Create a new book class (Product). Question 2 of this step has been implemented.

(2) Create a new BookShop class, which encapsulates the purchased book information.

(3) Create a new library class BookStore. A large number of books are stored in the library. Here, we use ArrayList to store and initialize some book information.

(4) Create a new Customer class Customer. Each Customer can get a shopping cart when entering the library. This shopping cart is implemented by HashMap. The book number is its key, and the bound BookShop is its value.

(5) Create a new test main class SY6_3_BuyCar.

Experimental results:

❀ 4. Title: complete the following practical projects under Eclipse (choose a title)

1.[SY6_4.java] design and implementation of student course selection system. A student can take multiple courses, a course can be selected by multiple students, but a course cannot be selected by one student multiple times.

Functional requirements:

(1) When running the program, a top-level menu is displayed first, as shown in Figure 6-1 below.

Figure 6-1 top level menu

(2) The meaning of each menu command: 0 means to exit the program, 1 means that students log in, and 2 means that the administrator can view which students have selected each course.

(3) The student login information is stored in the Students object of type Map in the StudentVDB class. In the login process, the student number or password is entered incorrectly for three times. If the three times are unsuccessful, the interface shown in Figure 7-1 will be returned. If the login is successful, the interface shown in Figure 6-2 will be displayed.

 

Figure 6-2 interface after students log in successfully

(4) Complete the functions corresponding to each command in the student interface. The course information is stored in the CourseVDB class. When a student enters "0", he will return to the interface shown in Figure 1. At this time, the student's course selection is over. You can wait for the next student to log in.

Design requirements: the following package structure is adopted. The sub package structure cannot be changed, but new classes or packages can be added.

(5) The main test class of this experiment is SY6_4.java

Experimental results:

☀️| III. experimental results

⭐ 1. Source code:

package EXPS.Exp06.com.xzit.sy6;

import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.Iterator;
/**
 * Class: 19 soft embedded 2
 * Student No.: 20190507223
 * Name: Xia Xu
 * Experiment time: May 25, 2020
 * The function of this program is to define LIST and access data
 */
public class SY6_1_LIST {
    public static void main(String[] args) {
        ArrayList<String> lis=new ArrayList<>();
        lis.add("College of information and Telecommunications");
        lis.add("College of Mathematics");
        lis.add("College of mechanical and electrical engineering");
        lis.add("College of Civil Engineering");
        lis.add("Food College");
        for(int i=0;i<lis.size();i++){
            System.out.println("The first"+(i+1)+"Data:"+" "+lis.get(i));
        }
        System.out.println("------------------");
        Iterator iterator=lis.iterator();
        int num=1;
        while (iterator.hasNext()){
            String node=(String) iterator.next();
            System.out.println("The first"+(num++)+"Data:"+" "+node);

        }
        System.out.println("----------");
        num=1;
        for(String node: lis){
            System.out.println("The first"+(num++)+"Data:"+" "+node);
        }
        System.out.println("----------");
        System.out.println("Current collection size:"+lis.size());
        String node= lis.get(2);
        System.out.println("The third element is: "+node);
        lis.remove(2);
        System.out.println("The updated third element is    "+lis.get(2)+"      "+"Collection size: "+lis.size());

    }
}

⭐ ⒋ 2. Source code:

package EXPS.Exp06.com.xzit.sy6;

import java.util.*;
/**
 * Class: 19 soft embedded 2
 * Student No.: 20190507223
 * Name: Xia Xu
 * Experiment time: May 25, 2020
 * The function of this program is to use Map to simulate book classification
 */
public class SY6_2_Map {
    public static void main(String[] args) {
        Map<String,Book> map=new HashMap<>();
        map.put("01",new Book("01","java Basics","A","Tsinghua Publishing House","2020-01",20.1f));
        map.put("02",new Book("02","C++Basics","B","Tsinghua Publishing House","2020-02",30.1f));
        map.put("03",new Book("03","python Basics","C","Tsinghua Publishing House","2020-03",40.1f));
        map.put("04",new Book("04","javaScript Basics","D","Tsinghua Publishing House","2020-04",50.1f));
        map.put("05",new Book("05","pascal Basics","E","Tsinghua Publishing House","2020-05",60.1f));
        Iterator<String> iterator=map.keySet().iterator();
        while(iterator.hasNext()){
            String key=iterator.next();
            Book node=map.get(key);
            System.out.println(node);
        }

        System.out.println("------------");
        System.out.println("The current collection size is"+map.size());
        iterator=map.keySet().iterator();
        List<String> delQue=new LinkedList<>();
        while(iterator.hasNext()){
            String key=iterator.next();
            Book node=map.get(key);
            if(node.getName().contains("java")){
                delQue.add(key);
            }
        }
        for(int i=0;i<delQue.size();i++){
            System.out.println("Deleted content:"+map.get(delQue.get(i)));
            map.remove(delQue.get(i));
        }
        System.out.println("Updated size:"+map.size());
    }
}

⭐ ⒋ 3. Source code:

package EXPS.Exp06.com.xzit.sy6;

/**
 * Class: 19 soft embedded 2
 * Student No.: 20190507223
 * Name: Xia Xu
 * Experiment time: May 25, 2020
 * The function of this program is to simulate shopping cart
 */
public class SY6_3_BuyCar {
    public static void main(String[] args) {
        Customer customer=new Customer();
        customer.put(BookStore.products.get(0));
        customer.put(BookStore.products.get(1));
        customer.put(BookStore.products.get(2));
        customer.put(BookStore.products.get(3));
        customer.put(BookStore.products.get(4));
        customer.put(BookStore.products.get(2));
        customer.list();
    }
}

⭐ ⅸ 4. Architecture & source code:

framework:

code:

package EXPS.Exp06.Exam01.src.com.xzit.main;

import EXPS.Exp06.Exam01.src.com.xzit.business.AdimBusiness;
import EXPS.Exp06.Exam01.src.com.xzit.business.StudentBusiness;
import EXPS.Exp06.Exam01.src.com.xzit.params.CourseVDB;
import EXPS.Exp06.Exam01.src.com.xzit.params.StudentVDB;
import EXPS.Exp06.Exam01.src.com.xzit.vo.Student;
/**
 * Class: 19 soft embedded 2
 * Student No.: 20190507223
 * Name: Xia Xu
 * Experiment time: May 25, 2020
 * The function of this program is to simulate the course selection system
 */
import java.util.Scanner;

public class Main {
    public  StudentVDB studentVDB=new StudentVDB();
    public  CourseVDB courseVDB=new CourseVDB();
    public  Scanner sc=new Scanner(System.in);

    public static void main(String[] args) {
        new Main();
    }
    public Main() {

        while (true){
            printTopMenu();
            int type= sc.nextInt();
            if(type==0){
                System.exit(0);
            }
            else if(type==1){
                StudentBusiness studentBusiness=new StudentBusiness(this);
                if(studentBusiness.login()==true){
                    studentBusiness.running();
                }
            }
            else if(type==2){
                sc.skip("\n");
                System.out.println("Please enter the administrator password");
                String pw=sc.nextLine();
                if(pw.equals("ImAdmin")){
                    AdimBusiness adimBusiness=new AdimBusiness(this);
                    adimBusiness.running();

                }
                else{
                    System.out.println("password error");
                }

            }
            else{
                System.out.println("illegal input");
            }
        }

    }
    public static void printTopMenu(){
        System.out.println("-------------Top menu---------------");
        System.out.println("|  0-sign out  1-Student login  2-Administrator action  |");
        System.out.println("-----------------------------------");
        System.out.println("Please enter a menu command (enter a number)");
    }

}

package EXPS.Exp06.Exam01.src.com.xzit.business;

import EXPS.Exp06.Exam01.src.com.xzit.main.Main;
import EXPS.Exp06.Exam01.src.com.xzit.vo.Course;
import EXPS.Exp06.Exam01.src.com.xzit.vo.Student;


public class AdimBusiness {
    public Main main;

    public AdimBusiness(Main main) {
        this.main = main;
    }
    public void running(){
        System.out.println("------administrator mode------");
        boolean flag=false;
        while (!flag){
            this.printmenu();
            int type=main.sc.nextInt();
            main.sc.skip("\n");
            if(type==0){
                flag=true;
            }
            else if(type==1){
                System.out.println("Enter the student number of the student( ID)");
                String ID=main.sc.nextLine();
                int res=this.QueryStuSelectedCourse(ID);
                if(res==-1){
                    System.out.println("No selected courses");
                }
                else if(res==0){
                    System.out.println("Student not found");
                }
            }
            else if(type==2){
                System.out.println("Enter course number( ID)");
                String ID=main.sc.nextLine();
                int res=this.QueryCouSelectedByStu(ID);
                if(res==-1){
                    System.out.println("No selected courses");
                }
                else if(res==0){
                    System.out.println("Course not found");
                }
            }
            else if(type==3){
                System.out.println("Add or remove? 0-return 1-add to 2-delete");
                String mulType=main.sc.nextLine();
                if(mulType.equals("1")){
                    System.out.println("Enter the student number of the student to be added( ID)");
                    String ID=main.sc.nextLine();
                    System.out.println("Enter name");
                    String name=main.sc.nextLine();
                    System.out.println("Set password");
                    String pw=main.sc.nextLine();
                    if(this.addStudent(ID,new Student(ID,name,pw))){
                        System.out.println("Added successfully");
                    }
                    else{
                        System.out.println("Failed to add. The account already exists");
                    }
                }
                else if(mulType.equals("2")){
                    System.out.println("Enter the student number of the student to delete( ID)");
                    String ID=main.sc.nextLine();
                    if(this.delStudent(ID)){
                        System.out.println("Delete succeeded");
                    }
                    else{
                        System.out.println("ID non-existent");
                    }

                }
            }
            else if(type==4){
                System.out.println("Add or remove? 0-return 1-add to 2-delete");
                String mulType=main.sc.nextLine();
                if(mulType.equals("1")){
                    System.out.println("Enter the course number to add( ID)");
                    String ID=main.sc.nextLine();
                    System.out.println("Enter course name");
                    String name=main.sc.nextLine();
                    if(this.addCourse(ID,new Course(ID,name))){
                        System.out.println("Added successfully");
                    }
                    else{
                        System.out.println("Failed to add. The course already exists");
                    }
                }
                else if(mulType.equals("2")){
                    System.out.println("Enter the course number of the course to delete( ID)");
                    String ID=main.sc.nextLine();
                    if(this.delCourse(ID)){
                        System.out.println("Delete succeeded");
                    }
                    else{
                        System.out.println("Course does not exist");
                    }

                }
            }
            else{
                System.out.println("illegal input");
            }
        }

    }
    public void printmenu(){
        System.out.println("");
        System.out.println("");
        System.out.println("|-=****************************Administrator menu************************=-|");
        System.out.println("| 0-return 1-Query the selected course list of specified students 2-Query the selected students of the specified course 3-Add (delete) students 4-Add (delete) courses|");
        System.out.println("-=**************************************************************=-");
    }
    public int QueryStuSelectedCourse(String ID){
        for(Student i:main.studentVDB.studentsDB){
            if(i.getId().equals(ID)){
                if (i.getCourse_Set().size()==0) return -1;
                for(Course j:i.getCourse_Set()){
                    System.out.println(j);
                }
                return 1;
            }

        }
        return 0;
    }
    public int QueryCouSelectedByStu(String ID){
        for (Course i:main.courseVDB.courseDB){
            if(i.getID().equals(ID)){
                if(i.getStudents_Set().size()==0) return -1;
                for(Student j:i.getStudents_Set()){
                    System.out.println(j);
                }
                return 1;
            }
        }
        return  0;
    }
    public boolean addStudent(String ID,Student newNode){
        for(Student i:main.studentVDB.studentsDB){
            if(i.getId().equals(ID)){
                return false;
            }
        }
        main.studentVDB.studentsDB.add(newNode);
        return true;
    }
    public boolean delStudent(String ID){
        return main.studentVDB.studentsDB.remove(ID);
    }
    public boolean addCourse(String ID,Course newNode){
        for(Course i:main.courseVDB.courseDB){
            if(i.getID().equals(ID)){
                return false;
            }
        }
        main.courseVDB.courseDB.add(newNode);
        return true;

    }
    public boolean delCourse(String ID){
        return main.courseVDB.courseDB.remove(ID);
    }
}

package EXPS.Exp06.Exam01.src.com.xzit.business;

import EXPS.Exp06.Exam01.src.com.xzit.main.Main;
import EXPS.Exp06.Exam01.src.com.xzit.vo.Course;
import EXPS.Exp06.Exam01.src.com.xzit.vo.Student;

import java.util.HashSet;

public class StudentBusiness {
    public Main main;
    public Student nowUser=null;

    public StudentBusiness(Main main) {
        this.main = main;
    }

    public StudentBusiness() {
    }

    public void running(){
        System.out.println("Welcome students"+nowUser.getName());

        boolean flag=false;
        while (flag==false){
            this.printMenu();
            int type=main.sc.nextInt();
            main.sc.skip("\n");
            if(type==0){
                flag=true;
            }
            else if(type==1){
                System.out.println("Enter query type 1-All elective courses 2-Selected elective courses");
                int queryType=main.sc.nextInt();
                QueryCourseList(queryType);
            }
            else if(type==2){
                System.out.println("Please enter the elective course number");
                String courseID=main.sc.next();
                if(addSelectCourse(courseID)==true){
                    System.out.println("Added successfully");
                }
                 else{
                    System.out.println("Failed to add. Please check whether the course has been added or does not exist");
                }
            }
            else if(type==3){
                System.out.println("Are you sure? Enter Y OK, otherwise return");
                String confirm=main.sc.nextLine();
                if(confirm.equals("Y")){
                    nowUser.setCourse_Set(new HashSet<>());
                    System.out.println("Delete complete");
                }


            }
            else if(type==4){
                System.out.println("Please enter the elective course number to delete");
                String courseID=main.sc.next();
                if(delSelectedCourse(courseID)==true){
                    System.out.println("Delete succeeded");
                }
                else{
                    System.out.println("Failed to delete. Please check whether you have taken this course");
                }
            }
            else{
                System.out.println("Invalid input");
            }

        }

    }
    public void printMenu(){
        System.out.println("");
        System.out.println("");
        System.out.println("|-=****************************Student menu************************=-|");
        System.out.println("| 0-return 1-Query course selection table 2-Add elective courses 3-Delete all selected courses 4-Delete a course|");
        System.out.println("-=**************************************************************=-");
    }
    public  boolean login(){
        int count=3;
        main.sc.skip("\n");
        while (count>0) {
            System.out.println("Please enter the account number(Student number):");
            String username=main.sc.nextLine();
            System.out.println("Please input a password:");
            String password=main.sc.nextLine();

            int flag=test_login(username,password);
            if(flag==1) return true;
            else if(flag==0)  System.out.println("Wrong password, you still have"+(--count)+"Second chance");
            else System.out.println("The user doesn't exist, you still have"+(--count)+"Second chance");
            if(count==0) System.out.println("Return to the main interface");
        }
        return  false;
    }
    public  int test_login(String username,String password){
        for (Student i:this.main.studentVDB.studentsDB) {
            String ID=i.getId();
            if(username.equals(ID)){
                if(i.getPassword().equals(password)){
                    nowUser=i;
                    return 1;
                }
                return 0;
            }

        }
        return -1;

    }
    public void QueryCourseList(int type){

        if (type==1) {
            if(main.courseVDB.courseDB.size()==0){
                System.out.println("No courses");
                return;
            }
            for(Course i:main.courseVDB.courseDB){
                System.out.println(i);
            }
        } else {
            if(nowUser.getCourse_Set().size()==0){
                System.out.println("No selected courses");
                return;
            }
            else{
                for (Course i:nowUser.getCourse_Set()){
                    System.out.println(i);
                }
            }
        }
    }
    public boolean addSelectCourse(String s){
        HashSet<Course> selectde=nowUser.getCourse_Set();
        for (Course i:selectde){
            if(i.getID().equals(s)) return false;
        }
        for (Course i:main.courseVDB.courseDB){
            if(i.getID().equals(s)){
                i.getStudents_Set().add(nowUser);
                nowUser.getCourse_Set().add(i);
                return  true;
            }
        }
        return  false;
    }

    public boolean delSelectedCourse(String s){
        HashSet<Course> selectde=nowUser.getCourse_Set();
        Course node=null;
        for (Course i:selectde){
            if(i.getID().equals(s)) {
                node=i;
            }
        }
        if (node!=null){
            nowUser.getCourse_Set().remove(node);
            return true;

        }
        return false;
    }
}

package EXPS.Exp06.Exam01.src.com.xzit.params;

import EXPS.Exp06.Exam01.src.com.xzit.vo.Course;

import java.util.ArrayList;
import java.util.List;

public class CourseVDB {
    public static List<Course> courseDB=new ArrayList<>();
    static {
        courseDB.add(new Course("xz01","C++Basics"));
        courseDB.add(new Course("xz02","Java Basics"));
        courseDB.add(new Course("xz03","Python Basics"));
        courseDB.add(new Course("xz04","Pascal Basics"));
        courseDB.add(new Course("xz05","Kotlin Basics"));
        courseDB.add(new Course("xz06","go Basics"));
    }
}

package EXPS.Exp06.Exam01.src.com.xzit.params;

import EXPS.Exp06.Exam01.src.com.xzit.vo.Student;

import java.util.ArrayList;
import java.util.List;

public class StudentVDB {
    public static List<Student> studentsDB=new ArrayList<>();
    static {
        studentsDB.add(new Student("201901","Zhao Yi","201901"));
        studentsDB.add(new Student("201902","Qian Er","201902"));
        studentsDB.add(new Student("201903","Sun San","201903"));
        studentsDB.add(new Student("201904","Li Si","201904"));
        studentsDB.add(new Student("201905","Friday","201905"));
        studentsDB.add(new Student("201906","Wu Liu","201906"));
        studentsDB.add(new Student("201907","Zheng Qi","201907"));
        studentsDB.add(new Student("201908","bastard","201908"));
    }
}

package EXPS.Exp06.Exam01.src.com.xzit.vo;

import java.util.HashSet;

public class Course {
    private String ID;
    private String name;
    private HashSet<Student> students_Set;

    public Course() {
    }

    public Course(String ID, String name) {
        this.ID = ID;
        this.name = name;
        this.students_Set=new HashSet<>();
    }

    public String getID() {
        return ID;
    }

    public void setID(String ID) {
        this.ID = ID;
    }

    public String getName() {
        return name;
    }

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

    public HashSet<Student> getStudents_Set() {
        return students_Set;
    }

    public void setStudents_Set(HashSet<Student> students_Set) {
        this.students_Set = students_Set;
    }

    @Override
    public String toString() {
        return "Course number: "+ID+"\t"+"Course name" +name;
    }
}

package EXPS.Exp06.Exam01.src.com.xzit.vo;

import java.util.HashSet;

public class Student {
    private String Id;
    private String name;
    private String password;
    private HashSet<Course> course_Set;

    public Student() {
    }

    public Student(String id,String name, String password) {
        this.Id = id;
        this.password = password;
        this.name=name;
        this.course_Set=new HashSet<>();
    }

    public String getId() {
        return Id;
    }

    public void setId(String id) {
        Id = id;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public HashSet<Course> getCourse_Set() {
        return course_Set;
    }

    public void setCourse_Set(HashSet<Course> course_Set) {
        this.course_Set = course_Set;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Student number: "+Id+"\t"+"full name :"+name;
    }
}

4, Experimental summary

Through this experiment, I understand the concept, architecture, classification and usage scenarios of Set; master the Set interface and main implementation classes; List interface and main implementation classes; Map interface and main implementation classes.

Understand the role of generics and master the application of type safety checking in collections.

Keywords: Java Algorithm Back-end

Added by IchBin on Thu, 09 Dec 2021 18:42:34 +0200