1. Project requirements
2. Software design structure
3. Preparation before design
Because we haven't learned the database yet, we use a Date class to store the company member data we need
Data class:
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; //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", "Jack Ma", "22", "3000"}, {"13", "2", "pony ", "32", "18000", "15000", "2000"}, {"11", "3", "Robin Li", "23", "7000"}, {"11", "4", "Qiang Dong Liu", "24", "7300"}, {"12", "5", "Lei Jun", "28", "10000", "5000"}, {"11", "6", "Ren Zhiqiang", "22", "6800"}, {"12", "7", "Liu Chuanzhi", "29", "10800","5200"}, {"13", "8", "Yang Yuanqing", "30", "19800", "15000", "2500"}, {"12", "9", "Shi Yuzhu", "26", "9800", "5500"}, {"11", "10", "Ding Lei", "21", "6600"}, {"11", "11", "Chao Yang Zhang", "25", "7100"}, {"12", "12", "Zhi Yuan Yang", "27", "9600", "4800"} }; //The following EQUIPMENTS array corresponds to the above EMPLOYEES array element one by one //PC :21, model, display //NoteBook:22, model, price //Printer :23, name, type public static final String[][] EQUIPMENTS = { {}, {"22", "association T4", "6000"}, {"21", "Dale", "NEC17 inch"}, {"21", "Dale", "Samsung 17 inches"}, {"23", "Canon 2900", "laser"}, {"21", "ASUS", "Samsung 17 inches"}, {"21", "ASUS", "Samsung 17 inches"}, {"23", "Epson 20 K", "Needle type"}, {"22", "HP m6", "5800"}, {"21", "Dale", "NEC 17 inch"}, {"21", "ASUS","Samsung 17 inches"}, {"22", "HP m6", "5800"} }; }
In addition, we also need a tool class to facilitate access to the keyboard
TSUtility class:
public class TSUtility { private static Scanner scanner = new Scanner(System.in); /** * * @Description This method reads the keyboard. If the user types any character in '1' - '4', the method returns. The return value is the character typed by the user. * @author shkstart * @date 2019 12:03:30 am, February 12 * @return */ 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') { System.out.print("Selection error, please re-enter:"); } else break; } return c; } /** * * @Description This method prompts and waits until the user presses enter and returns. * @author shkstart * @date 2019 12:03:50 am, February 12 */ public static void readReturn() { System.out.print("press Enter to continue..."); readKeyBoard(100, true); } /** * * @Description This method reads an integer with a length of no more than 2 bits from the keyboard and takes it as the return value of the method. * @author shkstart * @date 2019 12:04:04 am, February 12 * @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; } /** * * @Description Read 'Y' or 'N' from the keyboard and use it as the return value of the method. * @author shkstart * @date 2019 12:04:45 am, February 12 * @return */ 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; } }
4. Complete the entity class under domain first
After the preparation, according to the entity class model, we can see that architect, designer and programmer all inherit linearly from Employee.
According to the information in the figure, we can find that:
-
ID, name, age and salary are public attributes of employees in all positions
-
Programmers began to have more status attributes and collecting device attributes
-
Designers began to have more bonus attributes
-
Architects began to add stock attributes
So you can start designing these classes, and the code implementation is as follows
Employee classification:
public class Employee { private int id; private String name; private int age; private double salary; public int getId() { return id; } public void setId(int id) { this.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; } public Employee() { } public Employee(int id, String name, int age, double salary) { this.id = id; this.name = name; this.age = age; this.salary = salary; } //Encapsulate public properties to avoid subclasses rewriting too much repetitive code public String getDetail(){ return id + "\t" + name + "\t" + age + "\t" + salary; } //Here, we rewrite the toString method to display the personal information of an object instead of the address value when outputting it @Override public String toString() { return getDetail(); } }
Status enumeration class:
Status is a class defined by the project. It declares three object properties, which respectively represent the status of members. FREE - idle BUSY - joined the development team VOCATION - on vacation
public class Status { private final String NAME; private Status(String name) { this.NAME = name; } public static final Status FREE = new Status("FREE"); public static final Status VOCATION = new Status("VOCATION"); public static final Status BUSY = new Status("BUSY"); public String getNAME() { return NAME; } @Override //Override toString method public String toString() { return NAME; } }
public class Programmer extends Employee{ private int memberid; //The ID of the member in the development team private Status status = Status.FREE; private Equipment equipment; public int getMemberid() { return memberid; } public void setMemberid(int memberid) { this.memberid = memberid; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public Equipment getEquipment() { return equipment; } public void setEquipment(Equipment equipment) { this.equipment = equipment; } public Programmer() { } public Programmer(int id, String name, int age, double salary,Equipment equipment) { super(id, name, age, salary); this.equipment = equipment; } @Override public String toString() { return getDetail() + "\t programmer\t" + getStatus() + "\t\t\t\t\t" + getEquipment(); } //Encapsulate public properties to avoid subclasses rewriting too much repetitive code public String getCommon(){ return memberid + "/" + getId() + "\t\t" + getName() + "\t" + getAge() + "\t" + getSalary(); } //It is more convenient to display team member information public String getDetailsForTeam(){ return getCommon() + "\t programmer"; } } public class Designer extends Programmer{ private double bonus; public double getBonus() { return bonus; } public void setBonus(double bonus) { this.bonus = bonus; } public Designer() { } public Designer(int id, String name, int age, double salary, Equipment equipment , double bonus) { super(id, name, age, salary, equipment); this.bonus = bonus; } @Override public String toString() { return getDetail() + "\t designer\t" + getStatus() + "\t" + getBonus() + "\t\t\t" + getEquipment(); } public String getDetailsForTeam(){ return getCommon() + "\t designer\t" + getBonus(); } } public class Architect extends Designer { private int stock; public int getStock() { return stock; } public void setStock(int stock) { this.stock = stock; } public Architect() { } public Architect(int id, String name, int age, double salary, Equipment equipment, double bonus, int stock) { super(id, name, age, salary, equipment, bonus); this.stock = stock; } @Override public String toString() { return getDetail() + "\t architect \t" + getStatus() + "\t" + getBonus() + "\t" + getStock() + "\t" + getEquipment(); } public String getDetailsForTeam() { return getCommon() + "\t designer\t" + getBonus() + "\t" + getStock(); } }
Equipment is an interface, which is implemented by PC class, NoteBook class and Printer class respectively, and it is an attribute only started by Progrmmer class.
NoteBook has attributes: the model and price of the machine.
Properties of PC: model and display name
Printer attributes: the name and type of the device
According to the above information, we will implement the device interface.
Equipment:
public interface Equipment { String getDescription(); } public class NoteBook implements Equipment{ private String model; //Model of the machine private double price; //Price public NoteBook() { } public NoteBook(String model, double price) { this.model = model; this.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 class PC implements Equipment{ private String model; //Model of the machine private String display; //Indicates the display name public PC() { } public PC(String model, String display) { this.model = model; this.display = display; } 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 class Printer implements Equipment{ private String name; private String type; public Printer() { } public Printer(String name, String type) { this.name = name; this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
Here, the entity class under domino is completed!
5. Start the implementation of the service module
1. Design of namelistservice class
NameListService class is an operation on Data. It is responsible for encapsulating the Data in Data into Employee [] array and providing methods for related operation Employee [].
Analysis: we compare the class in the service module to a remote controller, which provides several functions to operate entity object data.
Property: an array of employees objects used to store objects
method:
① Construction method (build different objects according to the Data in the Data class, including Employee, Programmer, Designer and Architect objects, (polymorphic))
② Returns an array of all employee objects
③ Returns the specified employee object
import com.team.domain.*; //Import all entity classes under the domain module import static com.team.service.Data.*; //Import static methods and properties under the Data class (the class name can be omitted.) public class NameListService { private Employee[] employees; //attribute //constructor public NameListService(){ } //Returns an array of all employee objects public Employee[] getAllEmployees(){ return employees; } //Returns the specified employee object public Employee getEmployee(int id) { return null; } }
1.1 constructor
-
Create an Employee array based on the number of employees in the company
-
Get basic attributes such as employee type, ID, name, age, salary, etc
-
Create different employee classes (polymorphic) according to different employee position types and add them to the array
Code implementation:
public NameListService(){ employees = new Employee[EMPLOYEES.length]; for(int i = 0 ; i < employees.length ; i++){ int type = Integer.parseInt(EMPLOYEES[i][0]); //type int id = Integer.parseInt(EMPLOYEES[i][1]); //id String name = EMPLOYEES[i][2]; //full name int age = Integer.parseInt(EMPLOYEES[i][3]); //Age double salary = Double.parseDouble(EMPLOYEES[i][4]); //wages Equipment equipment; //Equipment (not every employee has equipment, and the assignment is declared here first) double bonus; //bonus int stock; //shares //The readability of numbers is too poor. We use our own defined constants to express employee types switch(type){ case EMPLOYEE: employee[i] = new Employee(id,name,age,salary); break; case PROGRAMMER: equipment = creatEquipment(i);//Because we need to select a device, we encapsulate the code into a function and complete it later employee[i] = new Employee(id,name,age,salary,equipment); break; case DESIGNER: equipment = creatEquipment(i); bonus = Double.parseDouble(EMPLOYEES[i][5]); employees[i] = new Employee(id,name,age,salary,equipment,bonus); break; case ARCHITECT: equipment = creatEquipment(i); bonus = Double.parseDouble(EMPLOYEES[i][5]); stock = Integer.parseInt(EMPLOYEES[i][6]); employees[i] = new Employee(id,name,age,salary,equipment,bonus,stock); break; } } }
Method of creating equipment:
private Equipment creatEquipment(int index){ Equipment equipment; int type = Integer.parseInt(EQUIPMENT[index][0]); //Equipment type String model = EQUIPMENT[index][1]; String info = EQUIPMENT[index][2]; double price; switch(type){ case PC: return new PC(model,info); case NoteBook: price = Double.parseDouble(EQUIPMENT[index][2]); return new NoteBook(model,price); case Printer; return new Printer(model,info); } return null; }
1.2 return the specified employee object
-
Find the employee in the array according to the id, and return if found
-
If it cannot be found, a custom exception class will be thrown (because the exception does not belong to the system's own exception, not because of our code error, but because of the customer's operation)
public class TeamException extends Exception{ static final long serialVersionUID = -33875229948L; public TeamException(){} public TeamException(String message){ super(message); } }
-
Here, we choose throws to throw an exception upward because this method will be called in the main view layer module, so we go there for unified processing
Code implementation:
public Equipment getEmployee(int id) throws TeamException{ for(int i = 0 ; i < employees.length ; i++){ if(id == employees[i].getID) { return employees[i]; } } throw new TeamException("The specified employee could not be found"); }
The complete code is as follows:
import com.team.domain.*; //Import all entity classes under the domain module import static com.team.service.Data.*; //Import static methods and properties under the Data class (the class name can be omitted.) public class NameListService { private Employee[] employees; //attribute //constructor public NameListService(){ employees = new Employee[EMPLOYEES.length]; for(int i = 0 ; i < employees.length ; i++){ int type = Integer.parseInt(EMPLOYEES[i][0]); //type int id = Integer.parseInt(EMPLOYEES[i][1]); //id String name = EMPLOYEES[i][2]; //full name int age = Integer.parseInt(EMPLOYEES[i][3]); //Age double salary = Double.parseDouble(EMPLOYEES[i][4]); //wages Equipment equipment; //Equipment (not every employee has equipment, and the assignment is declared here first) double bonus; //bonus int stock; //shares //The readability of numbers is too poor. We use our own defined constants to express employee types switch(type){ case EMPLOYEE: employee[i] = new Employee(id,name,age,salary); break; case PROGRAMMER: equipment = creatEquipment(i);//Because we need to select a device, we encapsulate the code into a function and complete it later employee[i] = new Employee(id,name,age,salary,equipment); break; case DESIGNER: equipment = creatEquipment(i); bonus = Double.parseDouble(EMPLOYEES[i][5]); employees[i] = new Employee(id,name,age,salary,equipment,bonus); break; case ARCHITECT: equipment = creatEquipment(i); bonus = Double.parseDouble(EMPLOYEES[i][5]); stock = Integer.parseInt(EMPLOYEES[i][6]); employees[i] = new Employee(id,name,age,salary,equipment,bonus,stock); break; } } } private Equipment creatEquipment(int index){ Equipment equipment; int type = Integer.parseInt(EQUIPMENT[index][0]); //Equipment type String model = EQUIPMENT[index][1]; String info = EQUIPMENT[index][2]; double price; switch(type){ case PC: return new PC(model,info); case NoteBook: price = Double.parseDouble(EQUIPMENT[index][2]); return new NoteBook(model,price); case Printer; return new Printer(model,info); } return null; } //Returns an array of all employee objects public Employee[] getAllEmployees(){ return employees; } //Returns the specified employee object public Equipment getEmployee(int id) throws TeamException{ for(int i = 0 ; i < employees.length ; i++){ if(id == employees[i].getID) { return employees[i]; } } throw new TeamException("The specified employee could not be found"); } }
NameListService class design completed!
2. Design of teamservice class
Analysis: the TeamService class is used to operate the members of the development team, such as adding, viewing, deleting, etc. the team members are required to be at least programmers. Because the team size is fixed, there is no need to have a parameter structure to open up the array, so it can be constructed without parameters by default.
Properties:
-
The count attribute is set as a static variable to set the unique ID in the team, that is, the memberID (each additional person creates a new ID in the way of self addition)
-
The MAX_MEMBER property is used to set the maximum number of people in the team, which is tentatively set to 5.
-
You need an array of Programmer objects to store development team members.
-
A total attribute is required to dynamically record the number of people in the development team
method:
-
Returns all objects of the current team
-
Add members to the team (there may be exceptions, consider the possibility of adding failure)
-
Remove members from the team (exceptions may also exist)
public class TeamService { private static int count = 1;//Class to ensure the uniqueness of the team ID private final int MAX_MEMBER = 5; private Programmer[] team = new Programmer[MAX_MEMBER]; private int total = 0; //Returns all objects of the current team public Programmer[] getTeam(){ return null; } //Add members to the team public void addMember(){ } //Remove member from team public void removeMember(){ } }
2.1 return the object array of the current team:
The team array cannot be returned directly here
//Wrong practice public Programmer[] getTeam(){ return team; }
This is problematic because the team array has a team size of max_ For the array under member, we just need the number of people in the current team. Suppose there are only two people in the team, but an array of five objects is returned, so there will be problems when traversing the array later.
Therefore, you should create a new array, which is sized according to the value of total
public Programmer[] getTeam(){ Programer[] team = new Programer[total]; for(int i = 0 ; i < team.length ; i++){ team[i] = this.team[i]; } return team; }
2.2 add designated employees to the development team
The addition operation is very simple, but what needs to be considered here is the failure of the addition
The failure information includes the following: the member is full and cannot be added. The member is not a developer. The employee cannot be added. The employee is already a member of a team in this development team. The employee is on vacation. The team cannot be added. There can only be one architect at most. There can only be two designers in the team. There can only be three programmers in the team
The code implementation is as follows:
public void addMember(Employee e) throws TeamException { if(total >= MAX_MEMBER){ throw new TeamException("The member is full and cannot be added"); } if(!(e instanceof Programmer)) { throw new TeamException("The member is not a developer and cannot be added") } Programmer p = (Programmer) e; //Transition down to call Programmer's getSatuus method //The code to determine whether the employee is on the development team is a little long, and we encapsulate it into a method if(isExist(p)){ throw new TeamException("The employee is already on the development team") } //You can choose to override the toString method of the Status class or p.getStatus.getName switch(p.getStatus){ case "BUSY": throw new TeamException("This member is already a team member"); case "VOCATION": throws new TeamException("The member is on vacation"); } //Judge whether the p to be added meets the requirements for the number of people in each type of work //Judging that there are too many programs, we can choose to package them into a function switch (isSelect(p)){ case 1: throw new TeamException("There can be at most one architect on the team"); case 2: throw new TeamException("There can be no more than two designers on the team"); case 3: throw new TeamException("There can be no more than three programmers on the team"); case 0: break; } // Once this position can be executed, it is proved that the above exceptions will not occur p.setStatus(Status.BUSY); //Change member status p.setMemberid(counter++); team[total++] = p; }
Determine whether p already exists in the current development team
private boolean isExist(Programmer p) {
for (int i = 0 ; i < total ; i++){
if(team[i].getId() == p.getId()){
return true;
}
}
return false;
}
Judge the situation in the team:
private int isSelect(Programmer p){
// Calculate the number of programmers, designers and architects in the existing development team
int numOfPro = 0,numOfDes = 0,numOfArch = 0;
for (int i = 0 ; i < total ; i++){
if (team[i] instanceof Architect){
numOfArch++;
}else if(team[i] instanceof Designer){
numOfDes++;
}else if(team[i] instanceof Programmer){
numOfPro++;
}
}
// Judge whether the p to be added meets the requirements for the number of people in each type of work
if (p instanceof Architect){
if (numOfArch >= 1){
return 1;
}
} else if (p instanceof Designer){
if (numOfDes >= 2){
return 2;
}
} else if (p instanceof Programmer) {
if (numOfPro >= 3){
return 3;
}
}
return 0; // Indicates that you can add
}
2.3 remove designated employees from the development team
Get the employee's team ID and traverse the team array. If there is one, let the latter fill in, and if there is no one, throw an exception
public void removeMember(int memberID) throws TeamException{ int i; for (i = 0 ; i < total ; i++){ if (team[i].getMemberid() == memberID){ team[i].setStatus(Status.FREE); break; } } if (i == total){ throw new TeamException("the employee with the specified memberID cannot be found"); } for (int j = i ; j < total ; j++){ team[j] = team[j+1]; } team[--total] = null; } }
TeamService class completed!
The complete code is as follows
import com.team.domain.Architect; import com.team.domain.Designer; import com.team.domain.Employee; import com.team.domain.Programmer; public class TeamService { private static int counter = 1; // It is used to automatically generate unique ID s in the team for new members of the development team private final int MAX_MEMBER = 5;;// The largest number of people in the development team private Programmer[] team = new Programmer[MAX_MEMBER]; private int total = 0; // Used to record the number of development teams added to the team //Returns an array of developers public Programmer[] getTeam(){ Programmer[] team = new Programmer[total]; for (int i = 0 ; i < team.length ; i++){ team[i] = this.team[i]; } return team; } // Add the specified employee to the development team public void addMember(Employee e) throws TeamException{ // The member is full and cannot be added if(total >= MAX_MEMBER){ throw new TeamException("The member is full and cannot be added"); } // The member is not a developer and cannot be added if (!(e instanceof Programmer)) { throw new TeamException("The member is not a developer and cannot be added"); } // The employee is already in the development team or on vacation Programmer p = (Programmer) e; //Transition down to call Programmer's getSatuus method switch (p.getStatus().getName()) { case "BUSY": throw new TeamException("The employee is already a member of a team"); case "VOCATION": throw new TeamException("The employee is on vacation and cannot be added"); } // The employee is already a member of a team if (isExist(p)){ throw new TeamException("The employee is already on the team"); } //Calculate the number of programmers, designers and architects in the existing development team //Judge whether the p to be added meets the requirements for the number of people in each type of work switch (isSelect(p)){ case 1: throw new TeamException("There can be at most one architect on the team"); case 2: throw new TeamException("There can be no more than two designers on the team"); case 3: throw new TeamException("There can be no more than three programmers on the team"); case 0: break; } // Once this position can be executed, it is proved that the above exceptions will not occur p.setStatus(Status.BUSY); p.setMemberid(counter++); team[total++] = p; } //Determine whether p already exists in the current development team private boolean isExist(Programmer p) { for (int i = 0 ; i < total ; i++){ if(team[i].getId() == p.getId()){ return true; } } return false; } //Judge the situation in the team private int isSelect(Programmer p){ //Calculate the number of programmers, designers and architects in the existing development team int numOfPro = 0,numOfDes = 0,numOfArch = 0; for (int i = 0 ; i < total ; i++){ if (team[i] instanceof Architect){ numOfArch++; }else if(team[i] instanceof Designer){ numOfDes++; }else if(team[i] instanceof Programmer){ numOfPro++; } } //Judge whether the p to be added meets the requirements for the number of people in each type of work if (p instanceof Architect){ if (numOfArch >= 1){ return 1; } } else if (p instanceof Designer){ if (numOfDes >= 2){ return 2; } } else if (p instanceof Programmer) { if (numOfPro >= 3){ return 3; } } return 0; } //Remove the employee of the specified member from the development team public void removeMember(int memberID) throws TeamException{ int i; for (i = 0 ; i < total ; i++){ if (team[i].getMemberid() == memberID){ team[i].setStatus(Status.FREE); break; } } if (i == total){ throw new TeamException("The specified was not found memberID Employees"); } for (int j = i ; j < total ; j++){ team[j] = team[j+1]; } team[--total] = null; } }
6. Implementation of view module
Implementation of TeamView class
TeamViewl class is not only a view layer that users can directly see, but also an interface that users can directly operate, such as the face of a program. We only provide several methods for users to operate data here.
Properties:
-
An object instance of the NameListService class is required
-
An object instance of the TeamService class is required
method:
-
Display the main menu and several control interfaces (the following methods are only used for calling the main menu methods)
-
List all members of the company in tabular form
-
Displays a list of team members
-
Add team members
-
Delete team member
There is also the most important method for the main method of the program entry: ① instantiate the TeamView class ② call the menu method
import com.team.domain.Employee; import com.team.domain.Programmer; import com.team.service.NameListService; import com.team.service.TeamException; import com.team.service.TeamService; public class TeamView { private NameListService listSvc = new NameListService; private TeamService teamSvc = new TeamService; //Main interface display and control method public void enterMainMeau(){ } //List all members of the company in tabular form private void listAllEmployees(){ } //Displays a list of team members private void getTeam(){ } //Implement add members private void addMember(){ } //Implement delete member private void deleteMember(){ } public static void main(String[] args){ //The main program only needs two lines of code TeamView view = new TeamView(); view.enterMainMeau(); } }
1. Implementation of main interface method
The main interface method needs to realize two functions:
-
Display interface menu
-
Provide options
public void enterMainMeau(){ boolean isFlag = true; char select = 0; while(isFlag){ //According to the demonstration requirements, it is found that the list of all members of the company does not need to be displayed when calling the team member information if(select != 1){ //Show member list listAllEmployees(); } System.out.print("1 - Team List 2 - add team members 3 - delete team members 4 - exit Please select (1-4): "); select = TSUtility.readMenuSelection(); // The call of tool class interacts with the keyboard switch(select){ case '1': getTeam(); break; case '2': addMember(); break; case '3': deleteMember(); break; case '4': System.out.print("confirm to exit (Y/N)"); char isExit = TSUtility.readConfirmSelection(); if (isExit == 'Y'){ isFlag = false; } break; } } }
2. Display member list
-
Receive all employees with one employee array
-
Display employee information in a loop
private void listAllEmployees(){ System.out.println("development team scheduling software -------------------------------- \ n"); Employee[] employees = listSvc.getAllEmployees(); if(employees.length == 0 || employees == null){ System.out.println("employee list is empty") } else { System. Out. Println ("ID \ tname \ t age \ t salary \ t position \ t status \ t bonus \ t stock \ t collecting equipment"); for(int i = 0 ; i < employees.length ; i++){ System.out.println(employees[i]); // The toString method has been overridden to directly return employee information } System.out.println("--------------------------------------------------------------"); } }
3. Display the list of team members
Same steps as above
private void getTeam(){ System.out.println("---------------- team member list ---------------------"); Programmer[] programmers = teamSvc.getTeam; if(team.length == 0 || team == null){ System.out.println("the development team currently has no members!"); }else { System. Out. Println ("TDI / ID \ tname \ t age \ t salary \ t position \ t bonus \ t stock"); for (int i = 0 ; i < team.length ; i++){ System.out.println(team[i].getDetailsForTeam()); // Call the method written in the member class to facilitate the output of information } } System.out.println("-----------------------------------------------------"); // Press enter to continue TSUtility.readReturn(); }
4. Add member method
-
Gets the ID of the member to be added
-
Get the member object through the method provided by NameListService (consider exception handling)
-
Add the object into the teamSvc array through the method provided by TeamService (consider exception handling)
private void addMember(){ System.out.println("---------------- add member ---------------------"); System.out.print("please enter the employee ID to be added:"); int id = TSUtility.readInt(); try{ Employee emp = listSvc.getEmployee(id); teamSvc.addMember(emp); System.out.println("added successfully!"); } catch(TeamException e) {/ / all exceptions thrown upward are handled uniformly here System.out.println("failed to add. Reason for failure:" + e.getMessage()); } // Press enter to continue TSUtility.readReturn(); }
5. Delete member method
Step above
private void deleteMember(){ System.out.println("---------------- delete member ---------------------"); System.out.print("please enter the TID of the employee to be deleted:"); int memberId = TSUtility.readInt(); System.out.print("confirm to delete (Y/N):"); char delOrNot = TSUtility.readConfirmSelection(); if (delOrNot == 'Y'){ try { teamSvc.removeMember(memberId); System.out.println("deletion succeeded!"); }catch (TeamException e){ System.out.println("deletion failed, failure reason" + e.getMessage()); } // Press enter to continue TSUtility.readReturn(); } }
View module completed!
The complete code is as follows:
import com.team.domain.Employee; import com.team.domain.Programmer; import com.team.service.NameListService; import com.team.service.TeamException; import com.team.service.TeamService; public class TeamView { private NameListService listSvc = new NameListService(); private TeamService teamSvc = new TeamService(); //Main interface display and control method public void enterMainMeau(){ boolean isFlag = true; char select = 0; while (isFlag){ if (seletc != 1){ listAllEmployees(); } System.out.print("1-Team list 2-Add team member 3-Delete team member 4-Exit, please select(1-4): "); menu = TSUtility.readMenuSelection(); switch (select){ case '1': getTeam(); break; case '2': addMember(); break; case '3': deleteMember(); break; case '4': System.out.print("Confirm whether to exit(Y/N)?"); char isExit = TSUtility.readConfirmSelection(); if (isExit == 'Y'){ isFlag = false; } break; } } } //List all members of the company in tabular form private void listAllEmployees() { System.out.println("-------------------------------Develop team scheduling software--------------------------------\n"); Employee[] employees = listSvc.getAllEmployees(); if (employees.length == 0 || employees == null){ System.out.println("Employee list is empty"); }else { System.out.println("ID\t full name\t Age\t wages\t position\t state\t bonus\t shares\t Receiving equipment"); for (int i = 0 ; i < employees.length ; i++){ System.out.println(employees[i]); } System.out.println("--------------------------------------------------------------"); } } //Show team member list action private void getTeam(){ System.out.println("--------------------Team member list---------------------"); Programmer[] team = teamSvc.getTeam(); if (team.length == 0 || team == null){ System.out.println("The development team currently has no members!"); }else { System.out.println("TDI/ID\t full name\t Age\t wages\t position\t bonus\t shares"); for (int i = 0 ; i < team.length ; i++){ System.out.println(team[i].getDetailsForTeam()); } } System.out.println("-----------------------------------------------------"); //Press enter to continue TSUtility.readReturn(); } //Implement the operation of adding members private void addMember() { System.out.println("---------------------Add member---------------------"); System.out.print("Please enter the employee to add ID: "); int id = TSUtility.readInt(); try { Employee emp = listSvc.getEmployee(id); teamSvc.addMember(emp); System.out.println("Successfully added!"); }catch (TeamException e){ System.out.println("Add failed. Reason for failure:" + e.getMessage()); } //Press enter to continue TSUtility.readReturn(); } //Implement delete member operation private void deleteMember(){ System.out.println("---------------------Delete member---------------------"); System.out.print("Please enter the name of the employee to delete TID: "); int memberId = TSUtility.readInt(); System.out.print("Are you sure you want to delete(Y/N): "); char delOrNot = TSUtility.readConfirmSelection(); if (delOrNot == 'Y'){ try { teamSvc.removeMember(memberId); System.out.println("Delete succeeded!"); }catch (TeamException e){ System.out.println("Deletion failed, failure reason" + e.getMessage()); } //Press enter to continue TSUtility.readReturn(); } } public static void main(String[] args) { TeamView view = new TeamView(); view.enterMainMeau(); } }