Customer management applet of object-oriented basic case!

catalogue

introduction

1, Case requirements

  2, Train of thought

3, Code implementation.

Source code again

customer class

Tool class

Test class

introduction

        Dear friends, today I'd like to share a classic beginner case, hoping to help you.

It's not easy to create. Ask for a free three company support!

1, Case requirements

        

l Simulate the implementation of a text-based interface < Customer information management software >
l Further master programming and debugging skills, and be familiar with object-oriented programming
l It mainly involves the following knowledge points:
Ø Use of class structures: properties, methods, and constructors
Ø Creation and use of objects
Ø Class encapsulation
Ø Declaring and using arrays
Ø Insertion, deletion and replacement of arrays
Ø Use of keywords: this

  2, Train of thought

          First, we should determine the method used in the case. Here we demonstrate the collection completion

        The second step is to complete the preparation of the user interface. Use the while loop and Switch statement. We also wrote a family account revenue and expenditure system for reference.

        The third step is to improve each functional part of the applet. First, add a customer interface and how to operate it,

                   Please select(1-5): 1

---------------------Add customer---------------------
Name: Tong Gang
 Gender: Male
 Age: 35
 Tel: 010-56253825
 Email: tongtong@atguigu.com
---------------------Add complete---------------------
         The interface is as above. If it is not difficult to implement the interface, but mainly functions, we should first create a customer class for our management and modification of customer information. Then the customer class should include member variables name, age, gender, phone and email. Construct methods and corresponding set, get, and methods. The code is as follows:
package com.Customer;

/**
 * @author wang
 * @date 2021/8/23
 */
public class Customer {
    //Member variable
    private String name;
    private char gender;
    private int age;
    private String phone;
    private String email;

    //Empty parameter structure
    public Customer() {

    }

    //Parametric structure
    public Customer(String name, char gender, int age, String phone, String email) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.phone = phone;
        this.email = email;
    }

    //set,get method
    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setGender(char gender) {
        this.gender = gender;
    }

    public char getGender() {
        return gender;
    }

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

    public int getAge() {
        return age;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getPhone() {
        return phone;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getEmail() {
        return email;
    }
}

         Let's go back to this interface. To add a customer, we should create a collection object and store the information we need to enter into the collection,

        Step 4: let's first implement the customer list to facilitate inspection in the middle.
Please select(1-5): 4

---------------------------Customer list---------------------------
Number name       Gender    Age telephone                   mailbox
 1    Tong Gang         male        forty-five     010-56253825   tong@abc.com
 2    Feng Jie         female        thirty-six     010-56253825   fengjie@ibm.com
 3    Lei Fengyang     male        thirty-two      010-56253825   leify@163.com
-------------------------Customer list complete-------------------------

         This interface is to directly traverse the collection and output it in turn. Pay attention to adjusting the format.

        Step 5: modify the customer interface
Please select(1-5): 2

---------------------Modify customer---------------------
Please select the customer number to be modified(-1 sign out): 1
 full name(Tong Gang): 
Gender(male): 
Age(35): 
Telephone(010-56253825): 
mailbox(tongtong@atguigu.com): tongg@atguigu.com
---------------------Modification completed---------------------

         Here we can use a customer ID as a basis to modify the customer.
To create a customer object, modify the attributes as in the first step,
Call the array.set () method to modify each specified element.
         Step 6: delete the customer interface
                   Please select(1-5): 3

---------------------Delete customer---------------------
Please select the customer number to be deleted(-1 sign out): 1
 Are you sure you want to delete(Y/N): y
---------------------Delete complete---------------------

The same is true here. Find customers by ID, delete the specified elements in the collection by using the array.remove() method of the collection, and add a select whether to delete statement.

         Step 7: exit the statement.

For the exit of the whole applet, write an exit judgment statement directly in the main method.

3, Code implementation.

         First of all, this code will use a tool class. I will enlarge the end of this tool class for your reference. This tool class will make our code cleaner and more effective and reduce the possibility of vulnerabilities. For reference only, you can also not use tools, but for our current knowledge, it is very difficult to do it, and it is easy to leak.

         The first step is to write the main interface, which I believe we are all familiar with, and achieve the goal through the while loop.

public class CustomerView {
    public static void main(String[] args) {
        ArrayList<Customer> array = new ArrayList<Customer>();
        Scanner sc = new Scanner(System.in);
        /**
         *              -----------------Customer information management software-----------------
         *
         *                                      1 Add customer
         *                                      2 Modify customer
         *                                      3 Delete customer
         *                                      4 Customer list
         *                                      5 sign out
         *
         *                                      Please select (1-5):_
         */
        while (true) {
            System.out.println("-----------------Customer information management software-----------------");
            System.out.println();
            System.out.println("\t\t\t\t" + "1 Add customer");
            System.out.println("\t\t\t\t" + "2 Modify customer");
            System.out.println("\t\t\t\t" + "3 Delete customer");
            System.out.println("\t\t\t\t" + "4 Customer list");
            System.out.println("\t\t\t\t" + "5 retreat           Out");
            System.out.print("Please select(1-5): ");
            char choice = CMUtility.readMenuSelection();
            System.out.println();
            switch (choice) {
                case '1':

                    addCustomer(array);
                    break;
                case '2':

                    updateCustomer(array);
                    break;
                case '3':

                    deleteCustomer(array);
                    break;
                case '4':

                    viewCustomer(array);
                    break;
                case '5':
                    System.out.print("5.sign out(y/n):");
                    char cho = CMUtility.readConfirmSelection();
                    if (cho == 'y' || cho == 'Y') {
                        System.out.println("Exit succeeded! Welcome to use next time");
                        System.exit(0);
                    } else if (cho == 'n' || cho == 'N') {
                        System.out.println("Returned successfully. Welcome to continue using!");
                        break;
                    }
            }
        }
    }

         When our customer selects the specified function key of the above code, it will enter the corresponding function area. What if she inputs 9 incorrectly? Here we call a method, char choice = CMUtility.readMenuSelection();, The tool class is directly used to provide us with a good method to ensure that it can accurately identify the customer's typing. Of course, it is not difficult to complete it by writing a judgment statement.

         When the customer enters 1, it enters the add customer page. As we said before, we can complete the requirements by adding data to the collection. Then we have created the collection object. How to implement it? Look at the code

public static void addCustomer(ArrayList<Customer> array) {
        System.out.println("---------------------Add customer---------------------");
        Scanner sc = new Scanner(System.in);
        //Create customer object
        Customer c = new Customer();
        System.out.print("full name:");
        String name = CMUtility.readString(11);
        System.out.print("Gender:");
        char gender = CMUtility.readChar();
        System.out.print("Age:");
        int age = CMUtility.readInt();
        System.out.print("Telephone:");
        String phone = CMUtility.readString(11);
        System.out.print("Email:");
        String email = CMUtility.readString(20);
        //Assign data to customer object
        c.setName(name);
        c.setAge(age);
        c.setGender(gender);
        c.setPhone(phone);
        c.setEmail(email);
        //Add customer object to collection
        array.add(c);
        //Add success prompt
        System.out.println("---------------------Add complete---------------------");

    }

         Next, after entering a customer, you should naturally view it. Otherwise, what's the use of entering a customer?

The view is also very simple, that is, the traversal collection we are familiar with

 public static void viewCustomer(ArrayList<Customer> array) {
        System.out.println("---------------------------Customer list---------------------------");
        System.out.println("number\t" + "full name\t" + "Gender\t" + "Age\t" + "Telephone\t\t\t\t" + "mailbox");

        for (int i = 0; i < array.size(); i++) {
            Customer c = array.get(i);
            System.out.println((i + 1) + "\t" + c.getName() + "\t" + c.getGender() + "\t" + c.getAge()
                    + "\t" + c.getPhone() + "\t\t" + c.getEmail());
        }
        System.out.println("-------------------------Customer list complete-------------------------");
    }

         Of course, for the sake of beauty, you must pay attention to this format. You can adjust it to the right one. Here, in java, you can use \ t to represent indentation and \ n to represent newline.

         Then, if the customer finds that his information is entered incorrectly and wants to modify it, what should he do? The customer chose to press 2. Obviously, pressing 2 won't have any response at present! So let's put the code first

public static void updateCustomer(ArrayList<Customer> array) {
        System.out.println("---------------------Modify customer---------------------");
        System.out.print("Please select the customer number to be modified(-1 sign out): ");
        Scanner sc = new Scanner(System.in);
        int id = sc.nextInt();
        int key = -1;
        if (id == key) {
            return;
        } else {
            int index = -1;
            for (int i = 0; i < array.size(); i++) {
                Customer c = array.get(i);
                if (i == (id - 1)) {
                    index = i;
                    break;
                }
            }
            if (index == -1) {
                System.out.println("The number you entered does not exist, please re-enter!");
            } else {
                System.out.print("New name:");
                String name = CMUtility.readString(20);
                System.out.print("New gender:");
                char gender = CMUtility.readChar();
                System.out.print("New age:");
                int age = CMUtility.readInt();
                System.out.print("New phone:");
                String phone = CMUtility.readString(11);
                System.out.print("New mailbox:");
                String email = CMUtility.readString(20);

                Customer c = new Customer();
                c.setName(name);
                c.setGender(gender);
                c.setAge(age);
                c.setPhone(phone);
                c.setEmail(email);

                array.set(index, c);
                System.out.println("---------------------Modification completed---------------------");

            }
        }

    }

         In fact, the idea is somewhat similar to that in the first part, but this is not added to the set, but found in the set and modified it. How to implement it? Of course, first of all, we use a judgment statement to judge whether it will be modified or not in the next step. We can define a key value of - 1 as a status. If the user enters - 1, the function will be launched and will not be modified. If the input is not - 1 but the customer he wants to modify, we will go to the next step. Because we didn't enter the number here, but we gave it in the function. We found that no, this number is actually the index position of our collection + 1, so we can directly modify the elements in our plan through the index, that is, our so-called number, which is 1, If we want to perform index correspondence here, we can subtract one from it accordingly, and we can accurately find the elements in the set we need to modify. Finally, the problem is solved by adding our modified elements to the collection through the position of the index index.

If the number is given by yourself, it's easier. Just use the equals method of String for comparison, or = = comparison for basic data types.

        The last step is to delete the customer.

This step is almost the same as modifying. First, find the customer you want to delete according to the number. Second, delete him from the collection.

public static void deleteCustomer(ArrayList<Customer> array) {
        System.out.print("Please select the customer number to be modified(-1 sign out): ");
        Scanner sc = new Scanner(System.in);
        int id = sc.nextInt();
        int key = -1;
        if (id == key) {
            return;
        } else {
            int index = -1;
            for (int i = 0; i < array.size(); i++) {
                Customer c = array.get(i);
                if (i == (id - 1)) {
                    index = i;
                    break;
                }
            }
            if (index == -1) {
                System.out.println("The number you entered does not exist, please re-enter!");
            } else {
                System.out.println("Are you sure you want to delete(Y/N): ");
                char choice = CMUtility.readConfirmSelection();
                if (choice == 'y' || choice == 'Y') {
                    array.remove(index);
                    System.out.println("Customer deleted successfully!");
                } else if (choice == 'n' || choice == 'N') {
                    System.out.println("Customer information not deleted!");
                }
            }
        }
    }
}

       

          Conclusion

Thank you for your reading. Welcome to praise and visit each other and make progress. Next, we will bring more interesting little things. Pay attention and don't get lost!

Another problem with this topic is how to save his data for the next time you start the applet. You are welcome to leave a message in the comment area!

Source code again

customer class

package com.Customer;

/**
 * @author wang
 * @date 2021/8/23
 */
public class Customer {
    //Member variable
    private String name;
    private char gender;
    private int age;
    private String phone;
    private String email;

    //Empty parameter structure
    public Customer() {

    }

    //Parametric structure
    public Customer(String name, char gender, int age, String phone, String email) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.phone = phone;
        this.email = email;
    }

    //set,get method
    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setGender(char gender) {
        this.gender = gender;
    }

    public char getGender() {
        return gender;
    }

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

    public int getAge() {
        return age;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getPhone() {
        return phone;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getEmail() {
        return email;
    }
}

Tool class

package com.Customer;
import java.util.Scanner;

/**
 CMUtility Tools:
 Encapsulating different functions into methods means that its functions can be used directly by calling methods without considering the specific function implementation details.
 */
public class CMUtility {
    private static Scanner scanner = new Scanner(System.in);
    /**
     Used to select the interface menu. This method reads the keyboard. If the user types any character in '1' - '5', the method returns. The return value is the character typed by the user.
     */
    public static char readMenuSelection() {
        char c;
        for (; ; ) {
            String str = readKeyBoard(1, false);
            c = str.charAt(0);
            if (c != '1' && c != '2' &&
                    c != '3' && c != '4' && c != '5') {
                System.out.print("Selection error, please re-enter:");
            } else break;
        }
        return c;
    }
    /**
     Read a character from the keyboard and use it as the return value of the method.
     */
    public static char readChar() {
        String str = readKeyBoard(1, false);
        return str.charAt(0);
    }
    /**
     Read a character from the keyboard and use it as the return value of the method.
     If the user enters directly without entering characters, the method will take defaultValue as the return value.
     */
    public static char readChar(char defaultValue) {
        String str = readKeyBoard(1, true);
        return (str.length() == 0) ? defaultValue : str.charAt(0);
    }
    /**
     Read an integer with a length of no more than 2 bits from the keyboard and take it as the return value of the method.
     */
    public static int readInt() {
        int n;
        for (; ; ) {
            String str = readKeyBoard(2, false);
            try {
                n = Integer.parseInt(str);
                break;
            } catch (NumberFormatException e) {
                System.out.print("Digital input error, please re-enter:");
            }
        }
        return n;
    }
    /**
     Read an integer with a length of no more than 2 bits from the keyboard and take it as the return value of the method.
     If the user enters directly without entering characters, the method will take defaultValue as the return value.
     */
    public static int readInt(int defaultValue) {
        int n;
        for (; ; ) {
            String str = readKeyBoard(2, true);
            if (str.equals("")) {
                return defaultValue;
            }

            try {
                n = Integer.parseInt(str);
                break;
            } catch (NumberFormatException e) {
                System.out.print("Digital input error, please re-enter:");
            }
        }
        return n;
    }
    /**
     Read a string whose length does not exceed limit from the keyboard and take it as the return value of the method.
     */
    public static String readString(int limit) {
        return readKeyBoard(limit, false);
    }
    /**
     Read a string whose length does not exceed limit from the keyboard and take it as the return value of the method.
     If the user enters directly without entering characters, the method will take defaultValue as the return value.
     */
    public static String readString(int limit, String defaultValue) {
        String str = readKeyBoard(limit, true);
        return str.equals("")? defaultValue : str;
    }
    /**
     The input used to confirm the selection. This method reads' Y 'or' N 'from the keyboard and takes it as the return value of the method.
     */
    public static char readConfirmSelection() {
        char c;
        for (; ; ) {
            String str = readKeyBoard(1, false).toUpperCase();
            c = str.charAt(0);
            if (c == 'Y' || c == 'N') {
                break;
            } else {
                System.out.print("Selection error, please re-enter:");
            }
        }
        return c;
    }

    private static String readKeyBoard(int limit, boolean blankReturn) {
        String line = "";

        while (scanner.hasNextLine()) {
            line = scanner.nextLine();
            if (line.length() == 0) {
                if (blankReturn) return line;
                else continue;
            }

            if (line.length() < 1 || line.length() > limit) {
                System.out.print("Input length (not greater than)" + limit + ")Error, please re-enter:");
                continue;
            }
            break;
        }

        return line;
    }
}

Test class

package com.Customer;

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

/**
 * @author wang
 * @date2021/8/23
 */
public class CustomerView {
    public static void main(String[] args) {
        ArrayList<Customer> array = new ArrayList<Customer>();
        Scanner sc = new Scanner(System.in);
        /**
         *              -----------------Customer information management software-----------------
         *
         *                                      1 Add customer
         *                                      2 Modify customer
         *                                      3 Delete customer
         *                                      4 Customer list
         *                                      5 sign out
         *
         *                                      Please select (1-5):_
         */
        while (true) {
            System.out.println("-----------------Customer information management software-----------------");
            System.out.println();
            System.out.println("\t\t\t\t" + "1 Add customer");
            System.out.println("\t\t\t\t" + "2 Modify customer");
            System.out.println("\t\t\t\t" + "3 Delete customer");
            System.out.println("\t\t\t\t" + "4 Customer list");
            System.out.println("\t\t\t\t" + "5 retreat           Out");
            System.out.print("Please select(1-5): ");
            char choice = CMUtility.readMenuSelection();
            System.out.println();
            switch (choice) {
                case '1':

                    addCustomer(array);
                    break;
                case '2':

                    updateCustomer(array);
                    break;
                case '3':

                    deleteCustomer(array);
                    break;
                case '4':

                    viewCustomer(array);
                    break;
                case '5':
                    System.out.print("5.sign out(y/n):");
                    char cho = CMUtility.readConfirmSelection();
                    if (cho == 'y' || cho == 'Y') {
                        System.out.println("Exit succeeded! Welcome to use next time");
                        System.exit(0);
                    } else if (cho == 'n' || cho == 'N') {
                        System.out.println("Returned successfully. Welcome to continue using!");
                        break;
                    }
            }
        }
    }

    /**
     * Add customer interface
     * Please select (1-5): 1
     * <p>
     * ---------------------Add customer---------------------
     * Name: Tong Gang String
     * Gender: male Char
     * Age: 35int
     * Tel: 010-56253825
     * Email: tongtong@atguigu.com
     * ---------------------Add complete---------------------
     */
    public static void addCustomer(ArrayList<Customer> array) {
        System.out.println("---------------------Add customer---------------------");
        Scanner sc = new Scanner(System.in);
        //Create customer object
        Customer c = new Customer();
        System.out.print("full name:");
        String name = CMUtility.readString(11);
        System.out.print("Gender:");
        char gender = CMUtility.readChar();
        System.out.print("Age:");
        int age = CMUtility.readInt();
        System.out.print("Telephone:");
        String phone = CMUtility.readString(11);
        System.out.print("Email:");
        String email = CMUtility.readString(20);
        //Assign data to customer object
        c.setName(name);
        c.setAge(age);
        c.setGender(gender);
        c.setPhone(phone);
        c.setEmail(email);
        //Add customer object to collection
        array.add(c);
        //Add success prompt
        System.out.println("---------------------Add complete---------------------");

    }

    /**
     * ---------------------------Customer list---------------------------
     * No. Name gender age telephone email
     * 1    Tong Gangnan 45 010-56253825 tong@abc.com
     * 2    Feng Jienu 36 010-56253825 fengjie@ibm.com
     * 3    Lei Fengyang male 32 010-56253825 leify@163.com
     * -------------------------Customer list complete-------------------------
     */
    public static void viewCustomer(ArrayList<Customer> array) {
        System.out.println("---------------------------Customer list---------------------------");
        System.out.println("number\t" + "full name\t" + "Gender\t" + "Age\t" + "Telephone\t\t\t\t" + "mailbox");

        for (int i = 0; i < array.size(); i++) {
            Customer c = array.get(i);
            System.out.println((i + 1) + "\t" + c.getName() + "\t" + c.getGender() + "\t" + c.getAge()
                    + "\t" + c.getPhone() + "\t\t" + c.getEmail());
        }
        System.out.println("-------------------------Customer list complete-------------------------");
    }

    /**
     * ---------------------Modify customer---------------------
     * Please select the customer number to be modified (- 1 exit): 1
     * Name (Tong Gang):
     * Gender (male):
     * Age (35):
     * Tel (010-56253825):
     * Mailbox( tongtong@atguigu.com):  tongg@atguigu.com
     * ---------------------Modification completed---------------------
     */
    public static void updateCustomer(ArrayList<Customer> array) {
        System.out.println("---------------------Modify customer---------------------");
        System.out.print("Please select the customer number to be modified(-1 sign out): ");
        Scanner sc = new Scanner(System.in);
        int id = sc.nextInt();
        int key = -1;
        if (id == key) {
            return;
        } else {
            int index = -1;
            for (int i = 0; i < array.size(); i++) {
                Customer c = array.get(i);
                if (i == (id - 1)) {
                    index = i;
                    break;
                }
            }
            if (index == -1) {
                System.out.println("The number you entered does not exist, please re-enter!");
            } else {
                System.out.print("New name:");
                String name = CMUtility.readString(20);
                System.out.print("New gender:");
                char gender = CMUtility.readChar();
                System.out.print("New age:");
                int age = CMUtility.readInt();
                System.out.print("New phone:");
                String phone = CMUtility.readString(11);
                System.out.print("New mailbox:");
                String email = CMUtility.readString(20);

                Customer c = new Customer();
                c.setName(name);
                c.setGender(gender);
                c.setAge(age);
                c.setPhone(phone);
                c.setEmail(email);

                array.set(index, c);
                System.out.println("---------------------Modification completed---------------------");

            }
        }

    }

    /**
     * Please select (1-5): 3
     * <p>
     * ---------------------Delete customer---------------------
     * Please select the customer number to be deleted (- 1 exit): 1
     * Confirm delete (Y/N): y
     * ---------------------Delete complete---------------------
     */
    public static void deleteCustomer(ArrayList<Customer> array) {
        System.out.print("Please select the customer number to be modified(-1 sign out): ");
        Scanner sc = new Scanner(System.in);
        int id = sc.nextInt();
        int key = -1;
        if (id == key) {
            return;
        } else {
            int index = -1;
            for (int i = 0; i < array.size(); i++) {
                Customer c = array.get(i);
                if (i == (id - 1)) {
                    index = i;
                    break;
                }
            }
            if (index == -1) {
                System.out.println("The number you entered does not exist, please re-enter!");
            } else {
                System.out.println("Are you sure you want to delete(Y/N): ");
                char choice = CMUtility.readConfirmSelection();
                if (choice == 'y' || choice == 'Y') {
                    array.remove(index);
                    System.out.println("Customer deleted successfully!");
                } else if (choice == 'n' || choice == 'N') {
                    System.out.println("Customer information not deleted!");
                }
            }
        }
    }
}

Tags: Java Mini Program

Posted on Mon, 06 Sep 2021 16:50:02 -0400 by jcran