The practice demo of extracting some functions from real projects
See the effect can be pulled to the end
brief introduction
**The software realizes the following functions:
1. When the software is started, create the company's partial member list (array) according to the given data
2. According to the menu prompt, based on the existing members of the company, set up a development team to develop a new project
3. The formation process includes inserting members into the team, or deleting a member from the team, and listing the current members of the team
4. Development team members include architects, designers and programmers
**
Be careful:
- Members are full.
- Not a developer
- Not a programmer or subclass
- The member is already a member of the team
- The member is on vacation
- This member is already another team member
- More than one architect in the team
- More than two designers in the team
- More than three programmers on the team
Can cause add failure
Knowledge points
- encapsulation
- inherit
- Interface
- enumeration
- polymorphic
- object array
- Two-dimensional array
- object reference
- abnormal
- static
- final
- Packaging class
Other knowledge points
structure
Employee general employee class
Programmer programmer class inherits ordinary employee class
Designer designer class inherits programmer class
Architect architect class inherits designer class
Equipment collecting equipment interface class
PC realizes the interface of receiving equipment desktop
Printer implements the interface printer class of collecting device
NoteBook implements the interface NoteBook class of collecting device
Status status enumeration class
TeamException custom exception class
Data data class
TSUtility for receiving keyboard input
NameListService is used to manage all employee information of the company
TeamService is used to manage all developers of the team
TeamView is used for function interface display and is responsible for the input and output of the interface
Code
Ordinary employees
package com.zjx.domain; /** * Ordinary employees * @author zjx * */ public class Employee { private int ID; //id private String name;//Full name private int age;//Age private double salary;//wages public Employee(int iD, String name, int age, double salary) { this.setID(iD); this.setName(name); this.setAge(age); this.setSalary(salary); } public int getID() { return ID; } public void setID(int iD) { ID = iD; } 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 double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } @Override public String toString() { return getInfo(); } /** * Convenient for designers and architects * @return */ public String getInfo(){ return this.getID() + "\t" + this.getName() + "\t" + this.getAge() + "\t" +this.getSalary(); } }
Programmer class
package com.zjx.domain; /** * Programmer, inherit Employee class * @author zjx * */ public class Programmer extends Employee { private Status state; //state private String position; //position private Equipment equipment; //Collar equipment private int tid;//Team id public Programmer(int iD, String name, int age, double salary,Equipment equipment) { super(iD, name, age, salary); this.setState(Status.FREE);//Default programmer state Free this.setPosition("Programmer");//Positions don't need to be transferred, because they're programmers this.setEquipment(equipment); } public int getTid() { return tid; } public void setTid(int tid) { this.tid = tid; } public Status getState() { return state; } public void setState(Status state) { this.state = state; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public Equipment getEquipment() { return equipment; } public void setEquipment(Equipment equipment) { this.equipment = equipment; } @Override public String toString() { return super.getInfo() + "\t" + this.getState() + "\t" +this.getPosition() + "\t\t\t" +this.getEquipment().getDescription(); } /** * Printing of team information * @return */ public String getDetails(){ return this.getTid() + "/" +super.getInfo() + "\t" + this.getPosition(); } }
Designer category
package com.zjx.domain; /** * Designer class inherits programmer * @author zjx * */ public class Designer extends Programmer{ private double bonus;//bonus public Designer(int iD, String name, int age, double salary, Equipment equipment, double bonus) { super(iD, name, age, salary, equipment); this.setPosition("Designer");//Change job description this.bonus = bonus; } public double getBonus() { return bonus; } public void setBonus(double bonus) { this.bonus = bonus; } @Override public String toString() { return super.getInfo() + "\t" + this.getState() + "\t" +this.getPosition() +"\t"+ this.getBonus() +"\t\t" + this.getEquipment().getDescription(); } @Override public String getDetails() { return super.getDetails()+"\t"+this.getBonus(); } }
Architect class
package com.zjx.domain; /** * Architect inherits Designer * @author zjx * */ public class Architect extends Designer{ private int stock;//shares public Architect(int iD, String name, int age, double salary, Equipment equipment, double bonus, int stock) { super(iD, name, age, salary, equipment, bonus); this.setPosition("architect");//Change job description this.stock = stock; } public int getStock() { return stock; } public void setStock(int stock) { this.stock = stock; } @Override public String toString() { return super.getInfo() + "\t" + this.getState() + "\t" +this.getPosition() +"\t"+ this.getBonus() +"\t" +this.getStock() +"\t" + this.getEquipment().getDescription(); } @Override public String getDetails() { return super.getDetails() + "\t" + this.getStock(); } }
Enumeration status class
package com.zjx.domain; /** * state * @author zjx * */ public enum Status { FREE,BUSY,VOCATION;//Three states }
Interface of collecting equipment
package com.zjx.domain; /** * Interface class of collecting equipment * @author zjx * */ public interface Equipment { public String getDescription();//Device information }
Collecting device interface implementation class PC
package com.zjx.domain; /** * Interface of collecting equipment implemented by computer class * @author zjx * */ public class PC implements Equipment { private String model;//brand private String display;//Description, dimensions, etc public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getDisplay() { return display; } public void setDisplay(String display) { this.display = display; } public PC(String model, String display) { this.setModel(model); this.setDisplay(display); } /** * Return the device description */ @Override public String getDescription() { return this.getModel()+"("+this.getDisplay()+")"; } }
Collecting device interface implementation class Notebook
package com.zjx.domain; /** * Notebook class implements the interface of collecting equipment * @author zjx * */ public class NoteBook implements Equipment { private String model;//brand private double price;//Price public String getModel() { return model; } public void setModel(String model) { this.model = model; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public NoteBook(String model, double price) { this.setModel(model); this.setPrice(price); } /** * Return the device description */ @Override public String getDescription() { return this.getModel()+"("+this.getPrice()+")"; } }
Interface implementation class Printer of collecting device
package com.zjx.domain; /** * Printer class implements interface of collecting equipment * @author zjx * */ public class Printer implements Equipment{ private String type;//type private String name;//Name public String getType() { return type; } public void setType(String type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Printer(String type, String name) { this.setType(type); this.setName(name); } /** * Return the device description */ @Override public String getDescription() { return this.getName()+"("+this.getType()+")"; } }
Data class data
package com.zjx.util; /** * Data class * @author zjx * */ public class Data { public static final int EMPLOYEE = 10; public static final int PROGRAMMER = 11; public static final int DESIGNER = 12; public static final int ARCHITECT = 13; public static final int PC = 21; public static final int NOTEBOOK = 22; public static final int PRINTER = 23; /** * Two dimensional array of employee information * Each one is an employee information * The first value of each employee information is the employee type */ //Employee : 10, id, name, age, salary //Programmer: 11, id, name, age, salary //Designer : 12, id, name, age, salary, bonus //Architect : 13, id, name, age, salary, bonus, stock public static final String[][] EMPLOYEES = { {"10", "1", "Duan Yu", "22", "3000"}, {"13", "2", "Linghu Chong", "32", "18000", "15000", "2000"}, {"11", "3", "Ren Woxing", "23", "7000"}, {"11", "4", "Zhang Sanfeng", "24", "7300"}, {"12", "5", "Zhou Zhi Luo", "28", "10000", "5000"}, {"11", "6", "Zhao Min", "22", "6800"}, {"12", "7", "Zhang Wuji", "29", "10800","5200"}, {"13", "8", "Wei Xiao Bao", "30", "19800", "15000", "2500"}, {"12", "9", "Yang Guo", "26", "9800", "5500"}, {"11", "10", "Little dragon maiden", "21", "6600"}, {"11", "11", "Guo Jing", "25", "7100"}, {"12", "12", "Huang Rong", "27", "9600", "4800"} }; /** * Two dimensional array of equipment information corresponding to employees. The first one is ordinary employees with equipment * Each piece corresponds to a device * The first value of each device corresponds to different types of devices */ //PC :21, model, display //NoteBook:22, model, price //Printer :23, type, name public static final String[][] EQIPMENTS = { {}, {"22", "association Y5", "6000"}, {"21", "Acer ", "AT7-N52"}, {"21", "DELL", "3800-R33"}, {"23", "laser", "Canon 2900"}, {"21", "ASUS", "K30BD-21 inch"}, {"21", "Haier", "18-511X 19"}, {"23", "Needle type", "EPSON 20 K"}, {"22", "HP m6", "5800"}, {"21", "association", "ThinkCentre"}, {"21", "ASUS","KBD-A54M5 "}, {"22", "HP m6", "5800"} }; }
Keyboard processing tools TSUtility
package com.zjx.util; import java.util.*; /** * Used to process incoming keyboard input * @author zjx * */ public class TSUtility { private static Scanner scanner = new Scanner(System.in); /** * The result of reading menu options can only be 1 2 3 4 * @return */ public static char readMenuSelection() { char c; for (; ; ) { //Can not be empty String str = readKeyBoard(1, false); c = str.charAt(0); if (c != '1' && c != '2' && c != '3' && c != '4') { System.out.print("Selection error, please re-enter:"); } else break; } return c; } /** * Receive keyboard input can be null and the maximum length is 100 */ public static void readReturn() { System.out.print("press Enter to continue..."); readKeyBoard(100, true); } /** * Receiving keyboard input cannot be empty, maximum length is 2 * @return */ 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; } /** * Receive keyboard input, cannot be empty * Uppercase letters up to one length * @return The final result can only be Y or N */ 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; } /** * Determine whether the maximum length and the maximum length of keyboard input are empty * @param limit Maximum length * @param blankReturn Can it be empty * @return */ private static String readKeyBoard(int limit, boolean blankReturn) { String line = ""; //If there is a next line while (scanner.hasNextLine()) { line = scanner.nextLine(); if (line.length() == 0) { if (blankReturn) return line; //If it can be null, return else continue; //Otherwise, continue to input } //Continue to enter if the length is less than 1 or greater than the maximum length if (line.length() < 1 || line.length() > limit) { System.out.print("Input length (not greater than" + limit + ")Error, please re-enter:"); continue; } break; } //Normal return return line; } }
Custom exception class
package com.zjx.service; /** * Custom exception class * @author zjx * */ public class TeamException extends RuntimeException { /** * Default serial number */ private static final long serialVersionUID = 1L; public TeamException() { super(); } public TeamException(String message) { super(message); } }
All employee management
package com.zjx.service; import com.zjx.util.Data; import com.zjx.domain.Architect; import com.zjx.domain.Designer; import com.zjx.domain.Employee; import com.zjx.domain.Equipment; import com.zjx.domain.NoteBook; import com.zjx.domain.PC; import com.zjx.domain.Printer; import com.zjx.domain.Programmer; /** * Function: used to manage all employee information of the company, including developers and non developers * Property: Employee[] emps; * Constructor: * Initialization of employees * Method: * Traverse all employee information and return * Get employee object according to employee number * @author zjx * */ public class NameListService { //attribute Employee[] emps;//Declaration array /** * Constructor initializer employee */ public NameListService(){ //Array space //The element length of the binary array is the total number of employees emps = new Employee[Data.EMPLOYEES.length]; //Array initialization for (int i = 0; i < emps.length; i++) { //Determine emps employee type //Create employee object of corresponding type according to employee type //Get employee category String type = Data.EMPLOYEES[i][0]; //Remove id int iD = Integer.parseInt(Data.EMPLOYEES[i][1]); //Full name String name = Data.EMPLOYEES[i][2]; //Age int age = Integer.parseInt(Data.EMPLOYEES[i][3]); //wages double salary = Double.parseDouble(Data.EMPLOYEES[i][4]); //Acquiring equipment Equipment equipment; switch (type) { case "10": //Employee emps[i] = new Employee(iD, name, age, salary); break; case "11": //Programmer //Acquiring equipment equipment = getEquipment(i); emps[i] = new Programmer(iD, name, age, salary, equipment); break; case "12": //Designer //Acquiring equipment equipment = getEquipment(i); //Get bonus double bonus = Double.parseDouble(Data.EMPLOYEES[i][5]); emps[i] = new Designer(iD, name, age, salary, equipment, bonus); break; case "13": //architect //Acquiring equipment equipment = getEquipment(i); //Get bonus double bonus2 = Double.parseDouble(Data.EMPLOYEES[i][5]); //Acquiring stock int stock = Integer.parseInt(Data.EMPLOYEES[i][6]); emps[i] = new Architect(iD, name, age, salary, equipment, bonus2, stock); break; } } } /** * Find corresponding subscript equipment according to employee subscript * @param i Employee subscript * @return Corresponding subscript equipment */ private Equipment getEquipment(int i) { //Get the type of corresponding equipment //The corresponding employee subscript index is each piece of equipment information //The first information of each device is the category String type = Data.EQIPMENTS[i][0]; switch (type) { case "21": //PC String model = Data.EQIPMENTS[i][1]; String display = Data.EQIPMENTS[i][2]; return new PC(model,display); case "22": //NoteBook String model2 = Data.EQIPMENTS[i][1]; double price = Double.parseDouble(Data.EQIPMENTS[i][2]); return new NoteBook(model2, price); case "23": //Printer String t = Data.EQIPMENTS[i][1]; String name = Data.EQIPMENTS[i][2]; return new Printer(t, name); } return null; } /** * Return all employee information * @return Employee information array */ public Employee[] getAllEmployees(){ return emps; } /** * * Get employee object according to employee number * @param id Employee number * @return Specific employees or exceptions */ public Employee getEmployee(int id){ for (int i = 0; i < emps.length; i++) { if (emps[i].getID() == id) { return emps[i]; //If the numbers are the same, return to the employee } } throw new TeamException("The employee does not exist"); } }
Team developer management
package com.zjx.service; import java.util.Arrays; import com.zjx.domain.Status; import com.zjx.domain.Architect; import com.zjx.domain.Designer; import com.zjx.domain.Employee; import com.zjx.domain.Programmer; /** * This class is used to demonstrate the design of the TeamService class * Function: used to manage all developers of the team * Properties: * final static int MAX_MENBERS =5; * Programmer[] pros = new Programmer[MAX_MENBERS];Developer array (holds all members of the team) * Up to five people in a team * Method: * Return to all developers * Add developer to pros array * Delete the developer specified in the pros array * @author zjx * */ public class TeamService { private static int counter = 1; //Record the teamId of each new member private static final int MAX_MEMBERS = 5; //Team maximum total private Programmer[] pros = new Programmer[MAX_MEMBERS];//Developer array private int total = 0;//Actual total /** * Return to actual developer * @return */ public Programmer[] getTeam(){ return Arrays.copyOf(pros, total); } /** * Add developer to pros array * @param e Staff to be added * If adding fails, return exception information */ public void addMember(Employee e){ //Members are full. if (total >= MAX_MEMBERS) { throw new TeamException("Member is full and cannot be added"); } //Not a developer not a programmer or subclass if (!(e instanceof Programmer)) { throw new TeamException("The member is not a developer and cannot be added"); } //The member is already a member of the team Programmer p = (Programmer)e; if (findEmployee(p)) { throw new TeamException("The member is already a member of this team and cannot be added"); } //The member is on vacation if (p.getState() == Status.VOCATION) { throw new TeamException("The member is on leave and cannot be added"); } //The member is already a team member if (p.getState() == Status.BUSY) { throw new TeamException("The member is already a team member and cannot be added"); } //Count the current number of architects, designers and programmers int as = 0;//architect int bs = 0;//Designer int ps = 0;//Programmer for (int i = 0; i < total; i++) { if (pros[i] instanceof Architect) { as++; }else if (pros[i] instanceof Designer) { bs++; }else{ ps++; } } //Only one architect in the team if (p instanceof Architect) { //If it's an architect if (as >= 1) { throw new TeamException("There can only be one architect in the team, cannot add"); } } //Only two designers in the team else if (p instanceof Designer) { //If it's a designer if (bs >= 2) { throw new TeamException("There can only be two designers in the team, unable to add"); } } //There are only three programmers on the team else { if (ps >= 3) { throw new TeamException("There are only three programmers in the team, unable to add"); } } //Normal addition //After adding, the actual number of people will be moved to one place pros[total++]=p; p.setTid(counter++);//After each new member's teamId is recorded++ p.setState(Status.BUSY); //Modify personnel status } /** * According to tid, delete the developer specified in pros array * @param tid */ public void removeMenber(int tid){ //1. Find the index location of the member corresponding to tid. If no exception object is found, continue to the next step int index = findIndex(tid); if (index == -1) { throw new TeamException("The team member you want to delete does not exist!"); } //Status updates for employees found pros[index].setState(Status.FREE); //2. Cycle forward for (int i = index; i < total - 1; i++) { pros[i] = pros[i+1]; //Set its team id to original minus 1 pros[i].setTid(pros[i].getTid()-1); } //3. Leave the last element blank //total-1 is the subscript of the last element //total if the actual element is 4, the last element subscript is 3 //4. The actual number of people is total. pros[total--] = null; //Value of current team id - 1 counter--; } /** * Find the id of the corresponding member according to the team id * @param tid * @return */ public int findIndex(int tid) { for (int i = 0; i < total; i++) { if (tid == pros[i].getTid()) { //If the passed in tid is the same as that of a member of the current team return i;//existence } } return -1; } /** * Find out if the employee already exists in the team * @param e * @return Does it exist? */ public boolean findEmployee(Programmer e) { // for (int i = 0; i < total; i++) { // if (e.getID() == pros[i].getID()) { // //If the employee id to be added is the same as one of the employee IDS in the array // return true; / / exists // } // } //Whether the tid of employee exists in the array int index = findIndex(e.getTid()); return index==-1?false:true; } }
Main interface class
package com.zjx.view; import com.zjx.domain.Employee; import com.zjx.domain.Programmer; import com.zjx.service.NameListService; import com.zjx.service.TeamService; import static com.zjx.util.TSUtility.*; /** * For function interface display, responsible for interface input and output * Functions: * Show all company employees * Main menu display * Add function * Deleting function * Team list * Sign out * @author zjx * */ public class TeamView { //Initialize employee Service NameListService nameListService = new NameListService(); //Comfort team operation Service TeamService ts = new TeamService(); /** * Show all company employees */ public void showAllEmps(){ System.out.println("-------------------------------Develop team scheduling software--------------------------------\n"); System.out.println("ID\t Full name\t Age\t wages\t position\t state\t bonus\t shares\t Collar equipment"); //Get an array of all employee objects Employee[] employees = nameListService.getAllEmployees(); for(Employee employee : employees){ System.out.println(employee); } System.out.println("-----------------------------------------------------------------------------"); } /** * Main menu */ public void enterMainMenu(){ boolean loop = true; do { //1. Call the method to display all employees showAllEmps(); //2. Display menu System.out.print("1-Team list 2-Add team member 3-Delete team member 4-Exit please select(1-4): "); //3. Receiving keyboard input and using tools //The result of key is only 1-4 char key = readMenuSelection(); switch (key) { case '1': showAllTeam(); break; case '2': add(); break; case '3': delete(); break; case '4': loop = exit(); break; } } while (loop); } /** * Add team members */ public void add(){ System.out.println("\n---------------------Add team members---------------------"); System.out.print("Please enter the employee to add ID: "); int id = readInt(); //Specific addition try { //1. Obtain a specific Employee object Employee according to id Employee employee = nameListService.getEmployee(id); //2. If the Employee exists, add the specified Employee object to the team ts.addMember(employee); System.out.println("Add success!"); } catch (Exception e) { System.out.println("Add failure: "+e.getMessage()); } finally{ //press Enter to continue readReturn(); } } /** * Delete team members */ public void delete(){ System.out.println("\n---------------------Delete team members---------------------"); System.out.print("Please enter the TID: "); int tid = readInt(); System.out.print("Confirm to delete(Y/N)"); char key = readConfirmSelection(); if (key == 'N') {//Not delete readReturn();//Press enter to continue }else{ try { //Are you sure you want to delete ts.removeMenber(tid); System.out.println("Delete successful"); } catch (Exception e) { System.out.println("Delete failed: "+e.getMessage()); }finally{ //press Enter to continue readReturn(); } } } /** * Show all team members */ public void showAllTeam(){ Programmer[] team = ts.getTeam(); if (team.length == 0) { System.out.println("At present, the team has no members"); readReturn(); } System.out.println("\n--------------------Team member list---------------------"); System.out.println("TID/ID\t Full name\t Age\t wages\t position\t bonus\t shares"); for(Programmer programmer : team){ System.out.println(programmer.getDetails()); } System.out.println("-----------------------------------------------------------------------------"); } /** * Exit menu */ public boolean exit(){ System.out.print("Are you sure you want to exit? Y/N: "); char key = readConfirmSelection(); return key!='Y';//If it is not equal to Y, it will return true to continue the loop } public static void main(String[] args) { new TeamView().enterMainMenu(); } }