Today, I knocked project02 with Mr. Song. Sometimes I can't keep up with the teacher's ideas and pause for a while. The places around may be mainly during interaction. In addition, I may not be particularly skilled in the use of basic knowledge. Next, I will analyze each class.
Customer class: M
The Customer class is the simplest of these classes. It consists of five attributes, the get and set methods corresponding to the five attributes, and two constructors (parameterless construction and construction with all attributes respectively). This class does not need to be analyzed. The code is as follows:
package project02.bean; /** * * @Description Customer Class to encapsulate customer information * @author * @version * @date 2021 1:51:09 PM, December 17 */ public class Customer { //Each attribute private String name; private char gender; private int age; private String phone; private String email; //get, set methods public void setName(String name) { this.name=name; } public String getName() { return name; } public char getGender() { return gender; } public void setGender(char gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } //constructor public Customer() { } public Customer(String name, char gender, int age, String phone, String email) { this.name = name; this.gender = gender; this.age = age; this.phone = phone; this.email = email; } }
CMUtility class
This class is mainly used to interact with keyboard input and judge whether the data entered by the keyboard meets the requirements. It is a simple toolkit. I directly copy this toolkit.
There is a readKeyBoard method, which is encapsulated. It is used for other methods in cmutity class to limit the number of input characters.
The readMenuSelection method is used to obtain the user's selection of functions. This method calls readKeyBoard.
The readChar method is used to read a character, in which an overload is formed in CMUtility. Another overloaded readChar method takes a formal parameter, and the formal parameter is the default character. It is judged by entering the number of characters on the keyboard, so as to produce whether the result is the default value or the first character of the keyboard.
The readString and readInt methods are similar to the readChar method.
The readConfirmSelection method is used to confirm your options. It is mainly used to confirm whether to exit
The code is as follows:
package project02.util; import java.util.*; public class CMUtility { public static void main(String[] args) { //System.out.println(readMenuSelection()); } private static Scanner scanner = new Scanner(System.in); private static String readKeyBoard(int limit,boolean blank){ for (;;) { String str = scanner.nextLine(); if (str.length()>0 && str.length()<=limit) { return str; } else if (blank) { return str; }else{ System.out.println("Please enter a length not exceeding"+limit+"Instructions"); } } } public static char readMenuSelection(){ //Get function selection char c; for(;;){ String str = readKeyBoard(1,false); c = str.charAt(0); if (c=='1' || c=='2' || c=='3' || c=='4' || c=='5' ) { return c; } else { System.out.println("Selection error, please re-enter."); } } } public static char readChar(){ //Get gender String str = readKeyBoard(1,false); return str.charAt(0); } public static char readChar(char defaultValue){ //When modifying gender information, press enter without entering information String str = readKeyBoard(1,true); return (str.length()==0)? defaultValue : str.charAt(0); } public static int readInt(){ //Get age int n; for(;;){ String str = readKeyBoard(2,false); try{ n = Integer.parseInt(str); return n; }catch (NumberFormatException e) { System.out.println("Digital input error, please re-enter."); } } } public static int readInt(int defaultValue){ //When modifying age information, press enter without entering information int n; for(;;){ String str = readKeyBoard(2,true); if (str.equals("")) { return defaultValue; } try{ n = Integer.parseInt(str); return n; }catch (NumberFormatException e) { System.out.println("Digital input error, please re-enter."); } } } public static String readString(int limit){ //Input of name, telephone and email return readKeyBoard(limit,false); } public static String readString(int limit,String defaultValue){ //When modifying name, phone and email, enter without entering information String str = readKeyBoard(limit,true); return str.equals("") ? defaultValue : str; } public static char readConfirmSelection(){ //Get confirmed input for(;;){ String str = readKeyBoard(1,false).toUpperCase(); char c = str.charAt(0); if (c=='Y' || c=='N') { return c; } else { System.out.println("Selection error, please enter Y/N"); } } } }
CustomerList class: C
It mainly manages the Customer class
Properties of this class:
1. The array customer of customer type is used to store customer data. In fact, it is essentially the address of each customer object.
2. total of type int is used to store the number of customers.
Constructor: a constructor CustomerList(int totalCustomer) with a formal parameter. The formal parameter describes the number of customers. During initialization, the customer attribute of this class is initialized.
Method: add, delete, modify and query + get all users + get the number of users
Needless to say, the method to obtain the number of users is very simple, just return total.
Add: the formal parameter is the object to be added. Judge before adding. The added position cannot exceed the length of the array. After adding, let total++
Delete: for the linear structure of array, deleting an element at a certain position requires subsequent elements to be supplemented, and the element content of the original last position becomes null. First judge the index. The index cannot exceed the boundary, and cannot exceed the number of existing customers, that is, total. You need to take the value of the next one from the index position to the last position. In fact, it is also the address of the next one. The last position of the object array is set to null to complete the deletion operation. Here is a note: customer[i]=customer[i+1]; When fetching the following address, i+1 should be set to total, so the judgment condition of the for loop should be I < total-1.
Change: if the formal parameter is an index and an object of Customer type to be changed, the index cannot cross the boundary. The change is actually to assign the address of the object passing in the formal parameter to the element at the index position in the array.
Query: to obtain the customer content at the specified location, first judge the index. The index cannot cross the boundary. If it does not cross the boundary, directly return the value at the index location of the object array. The value returned here is still an address.
Get all users: a new object array is constructed here to accept the existing elements in the original object array. The size of the newly constructed array is total. Because not every position in the original object array has a customer value, and those not assigned later are null. All user information can be obtained by traversing the newly constructed array.
In this class, when the constructor initializes, it constructs a customer object of customer array type. Some subsequent operations are aimed at this array. Adding, deleting, modifying and querying is actually adding, deleting, modifying and querying this array.
package project02.service; import project02.bean.Customer; /** * * @Description Customer The object management module is responsible for adding, deleting, modifying, querying and traversing the Customer object (array management) * @author * @version * @date 2021 1:53:00 PM, December 17 */ public class CustomerList { //attribute private Customer[] customer; private int total=0; //constructor /** * Initializes the constructor of the customer array * @param totalCustomer */ public CustomerList(int totalCustomer) { customer=new Customer[totalCustomer]; } //method /** * * @Description Adds the specified customer to the array * @author * @date 2021 2:35:46 PM, December 17 * @param customer * @return true is returned after adding successfully and false is returned after adding failed */ public boolean addCustomer(Customer customer) { if(total<this.customer.length) { this.customer[total++]=customer; return true; }else { return false; } } /** * * @Description Modify customer information at the specified location * @author * @date 2021 2:43:17 PM, December 17 * @param index * @param cust * @return true:Modification succeeded. false: modification failed */ public boolean replaceCustomer(int index,Customer cust) { if(index>0&&index<total) { /* * Scanner sca=new Scanner(System.in); String newName=sca.next(); int * newAge=sca.nextInt(); String newEmail=sca.next(); String * newGender=sca.next(); String newPhone=sca.next(); * customer[index].setName(newName); customer[index].setAge(newAge); * customer[index].setEmail(newEmail); * customer[index].setGender(newGender.charAt(0)); * customer[index].setPhone(newPhone); */ customer[index]=cust; return true; }else { return false; } } /** * * @Description Delete customer at specified location * @author * @date 2021 December 17, 2013 3:00:25 PM * @param index * @return true: Deletion succeeded. false: deletion failed */ public boolean deleteCustomer(int index) { if(index>0&&index<total) { for(int i=index;i<total-1;i++) //Note that the 0 subscript of the array begins { customer[i]=customer[i+1]; } //The last element with data needs to be set to null customer[total-1]=null; total--; return true; }else { return false; } } /** * * @Description Get all customer information * @author * @date 2021 December 17, 2013 3:10:39 PM * @return */ public Customer[] getAllCustomers() { Customer[] cust=new Customer[total]; for(int i=0;i<cust.length;i++) { cust[i]=customer[i]; //The address value is copied } return cust; } /** * * @Description Gets the customer at the specified location * @author * @date 2021 December 17, 2013 3:14:48 PM * @return */ public Customer getCustomer(int index) { if(index<0||index>=total) { return null; } return customer[index]; } /** * * @Description Get the number of customers * @author * @date 2021 December 17, 2013 3:17:13 PM * @return */ public int getTotal() { return total; } }
CustomerView class: V
This is a class that mainly interacts with users. The main function is also in this class. The main function is very simple. Build an object of this class in this class, and the object calls the enterMainMenu() method to enter the menu.
enterMainMenu() method:
Display the information of the user interface. Select from the read in menu in the CMUtility toolkit, which is the same as item 1, or use switch to classify the input results.
One operation is performed for each selection. There are add customer, modify customer, delete customer, display customer list and exit.
There is no need to introduce the exit operation, prompt whether to exit, obtain the typed data from the keyboard, and judge whether to exit through the typed data. Here, judge isfall as an identifier to jump out of the loop.
Adding a customer: encapsulate the input information into a new object by prompting and using the CMUtility toolkit. The return value of the addCustomer method in the customerList is boolean. Judge whether the addition is successful by judging its return value.
Modify customer: when modifying a customer, it may appear that the search index entered by the customer exceeds the content in the object array, so a circular search is carried out. The first step of modifying a customer is to find the customer first. If it cannot be found, the user will be prompted. If the customer is found, the user will be prompted first to enter the customer information to be modified, Prompt the customer to modify the previous information when entering the information again. After entering this information, create a new object to encapsulate the data just entered, and then modify it by using the modification method in the customerList class. Note that one of the formal parameters entered at this time is the position of the original object in the array. At this time, it should be the number - 1 entered by the customer, because the array starts from 0. The return value of the change command is also of boolean type, and its return value determines whether the modification is successful or failed.
Delete customer: the same as the above steps of modifying a customer. First find the customer, and then prompt the user whether to delete it. If you delete it, call the delete method in the customerList class. The return value of the delete method is also of boolean type. Whether the deletion is successful is judged by the return value. The input parameter of the deletion method is also the number num-1 entered by the user. The principle is the same as above.
Display Customer list: first check whether there are customers, that is, whether the value of Total is 0. The newly set variable undertakes the getTotal method in the customerList class. If there are customers, call the getAllCustomers() method in the customerList class to undertake with an array of Customer type. At this time, each element of the array is a Customer object (but actually the address of the stored Customer object). By traversing the array, the array element. Method (at this time, the array element is of Customer type, so you can call the get/set method in the Customer class) to obtain the function of displaying the Customer list.
The code is as follows:
package project02.view; import project02.bean.Customer; import project02.service.CustomerList; import project02.util.CMUtility; /** * * @Description The main module is responsible for menu display and user operation * @author * @version * @date 2021 December 17, 2014 1:54:47 PM */ public class CustomerView { private CustomerList customerList=new CustomerList(10); //constructor public CustomerView() { Customer customer=new Customer("james", 'male', 37, "13222222222", "james@gmail.com"); customerList.addCustomer(customer); } //Main function public static void main(String[] args) { CustomerView view =new CustomerView(); view.enterMainMenu(); } //method /** * * @Description Method for displaying customer information management software interface * @author * @date 2021 December 17, 2013 3:26:28 PM */ public void enterMainMenu() { boolean isFalg=true; while(isFalg) { System.out.println("\n--------------Customer information management software----------------\n"); System.out.println("\t\t 1 Add customer"); System.out.println("\t\t 2 Modify customer"); System.out.println("\t\t 3 Delete customer"); System.out.println("\t\t 4 Customer list"); System.out.println("\t\t 5 sign out\n"); System.out.print("\t Please select(1-5):"); char menu=CMUtility.readMenuSelection(); switch(menu) { case'1': addNewCustomer(); break; case'2': modifyCustomer(); break; case'3': deleteCustomer(); break; case'4': listAllCustomers(); break; case'5': System.out.print("Confirm whether to exit(Y/N)"); char isExit=CMUtility.readConfirmSelection(); if(isExit=='Y') { isFalg=false; } break; } } } /** * * @Description Add customer action * @author * @date 2021 December 17, 2013 3:25:08 PM */ private void addNewCustomer() { System.out.println("-----------Add customer----------"); System.out.print("full name:"); String name = CMUtility.readString(10); System.out.print("Gender:"); char gender=CMUtility.readChar(); System.out.print("Age:"); int age = CMUtility.readInt(); System.out.print("Telephone:"); String phone = CMUtility.readString(13); System.out.print("Email:"); String email = CMUtility.readString(30); //Encapsulate the above data into objects Customer customer=new Customer(name, gender, age, phone, email); boolean isSuccess=customerList.addCustomer(customer); if(isSuccess==true) { System.out.println("--------------Add complete----------"); }else { System.out.println("------------Customer directory is full, failed to add-------"); } } /** * * @Description Modify customer actions * @author * @date 2021 December 17, 2013 3:25:30 PM */ private void modifyCustomer() { System.out.println("------------------Modify customer------------"); Customer cust; //The declaration is outside, modified in the loop, and can be used in addition to the loop int num; while(true) { System.out.print("Please select the customer number to be modified(-1 sign out)"); num = CMUtility.readInt(); if(num==-1) { return; //break; All can } cust=customerList.getCustomer(num-1);//num-1 here is because the user's input of 1 is equivalent to the 0th element in the operation array if(cust==null) { System.out.println("The specified user cannot be found!"); }else//The corresponding user was found { break;//Jump out of while loop } } //Modify customer information System.out.println("full name("+cust.getName()+"):"); String name = CMUtility.readString(10, cust.getName());//No modification, still according to the original System.out.println("Gender("+cust.getGender()+"):"); char gender = CMUtility.readChar(cust.getGender()); System.out.println("Age("+cust.getAge()+"):"); int age = CMUtility.readInt(cust.getAge()); System.out.println("Telephone("+cust.getPhone()+"):"); String phone = CMUtility.readString(13, cust.getPhone()); System.out.println("mailbox("+cust.getEmail()+"):"); String email = CMUtility.readString(30, cust.getEmail()); Customer newCust=new Customer(name, gender, age, phone, email); boolean isReplaced= customerList.replaceCustomer(num-1, newCust);//The num-1 here is because the num-1 entered by the user is the number of positions to be operated in the array if(isReplaced) { System.out.println("--------------Modification completed-----------"); }else { System.out.println("--------------Modification failed-----------"); } } /** * * @Description Delete customer action * @author * @date 2021 December 17, 2013 3:25:39 PM */ private void deleteCustomer() { System.out.println("------------------------Delete customer--------------"); Customer cust; int num; while(true) { System.out.print("Please select the number of the customer to be deleted(-1 sign out)"); num = CMUtility.readInt(); if(num==-1) { return; } cust = customerList.getCustomer(num-1);// if(cust==null) { System.out.println("The specified customer cannot be found!"); }else { break; } } //The specified customer was found System.out.print("Are you sure to delete(Y/N)"); char isDelete = CMUtility.readConfirmSelection(); if(isDelete=='N') { return; }else { boolean isDeleteSuccess = customerList.deleteCustomer(num-1);//The principle of num-1 is the same as above if(isDeleteSuccess) { System.out.println("-----------------Delete succeeded----------"); }else { System.out.println("-----------------Deletion failed----------"); } } } /** * * @Description Display customer list action * @author * @date 2021 December 17, 2013 3:26:10 PM */ private void listAllCustomers() { System.out.println("-----------------Customer list------------\n"); int total = customerList.getTotal(); if(total==0) { System.out.println("No customer record!"); }else { System.out.println("number\t full name\t Gender\t Age\t Telephone\t\t mailbox"); Customer[] allCustomers = customerList.getAllCustomers(); for(int i=0;i<allCustomers.length;i++) { System.out.println((i+1)+"\t" +allCustomers[i].getName()+"\t" +allCustomers[i].getGender()+"\t"+allCustomers[i].getAge()+"\t"+allCustomers[i].getPhone()+"\t"+allCustomers[i].getEmail()); } } System.out.println("-----------------Customer list complete--------\n"); } }
The above is the analysis of these four classes. Except for the tool class, the remaining three classes just reflect the programming idea of MVC. The combination of model, view and control becomes a small project.
I've been watching, typing and analyzing this small project all day today. The programming ideas in it are really worth learning. For example, when making modifications, build a new object, modify the address in the array to complete the modification task, etc. there are still some gains after careful taste. Rush, you can't give up!