实操五

知识点范围:异常和常用类

一、选择题

  1. 以下代码的执行结果是( C )。(选择1项)
public class Test {
    public static void main(String args[]) {
        try {
            System.out.println("try");
            return;
        } catch (Exception e) {
            System.out.println("catch");
        } finally {
            System.out.println("finally");
        }
    }
}
    • A:
try
catch
finally
    • B:
catch
finally
    • C:
try
finally
    • D:
try
catch

解析:
无论是否捕获到异常,finally中的代码总会执行,即使在try或catch中执行了return,依然会先执行完毕finally之后,再执行return。

  1. 在异常处理中,释放资源、关闭文件等操作一般由( C )来完成。(选择1项)
    • A:try子句
    • B:catch子句
    • C:finally子句
    • D:throw子句

解析:
无论是否捕获到异常,finally中的代码总会执行,所以例如释放资源、关闭文件等必须要执行操作一般都会放到finally中。

  1. 编译并运行如下Java程序,将输出( D )。(选择1项)
public class Test {
    public static void main(String[] args) {
        try {
            int num1 = 2;
            int num2 = 0;
            int result = num1 / num2;
            System.out.println(result);
            throw new NumberFormatException();
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.print("1");
        } catch (NumberFormatException e) {
            System.out.print("2");
        } catch (Exception e) {
            System.out.print("3");
        } finally {
            System.out.print("4");
        }

        System.out.print("5");
    }
}
    • A:134
    • B:2345
    • C:1345
    • D:345

解析:
因为num2值是0,所以在执行int result = num1 / num2;语句时会报ArithmeticException,该异常会被catch (Exception e) {}语句块捕获,所以程序不会异常退出,而是先执行System.out.print("3");,然后执行finally中的System.out.print("4");和之后的System.out.print("5");

  1. 阅读如下Java代码,其中错误的行是( AC )。(选择2项)
public class Student {
    private String stuId;

    public void setStuId(String stuId) throw Exception {// 1
        if (stuId.length() != 4) {// 2
            throws new Exception("学号必须为4位!");// 3
        } else {
            this.stuId = stuId;//4
        }
    }
}
    • A:1
    • B:2
    • C:3
    • D:全部正确

解析:


image.png
  1. 阅读如下Java代码,在控制台输入“-1”,执行结果是( B )。(选择1项)
public class Demo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("请输入数字:");

        try {
            int num = input.nextInt();

            if (num < 1 || num > 4) {
                throw new Exception("必须在1-4之间!");
            }
        } catch (InputMismatchException e) {
            System.out.println("InputMismatchException");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
    • A:输出:InputMismatchException
    • B:输出:必须在1-4之间!
    • C:什么也没输出
    • D:编译错误

解析:
-1小于1,所以会执行throw new Exception("必须在1-4之间!");,并被catch (Exception e) {}捕获,然后执行System.out.println(e.getMessage());

  1. 以下选项中关于int和Integer的说法错误的是( BD )。(选择2项)
    • A:int是基本数据类型,Integer是int的包装类,是引用数据类型
    • B:int的默认值是0,Integer的默认值也是0
    • C:Integer中封装了属性和方法,可以提供更多的功能
    • D:Integer i=5;语句在JDK1.5之后可以正确执行,使用了自动拆箱功能

解析:

  • A选项:八种基本数据类型都有自己对应的包装类,包装类属于引用数据类型,正确
  • B选项:包装类属于引用数据类型,所以默认值是null,错误
  • C选项:包装类可以定义属性和方法,基本数据类型则不可以,正确
  • D选项:JDK1.5新增了自动拆/装箱功能,int a = new Integer(1);属于自动拆箱,Integer i=5;属于自动装箱,错误
  1. 分析如下Java代码,该代码编译后的运行结果是( D )。(选择1项)
public class Demo {
    public static void main(String[] args) {
        String str = null;
        str.concat("abc");
        str.concat("def");
        System.out.println(str);
    }
}
    • A:null
    • B:abcdef
    • C:编译错误
    • D:运行时出现NullPointerException异常

解析:
引用数据类型如果值为null,虽然编译不会出现问题,但是运行时一旦执行任何方法都会报NullPointerException。

  1. 以下关于String类的代码的执行结果是( B )。(选择1项)
public class Test {
    public static void main(String args[]) {
        String s1 = new String("bjsxt");
        String s2 = new String("bjsxt");

        if (s1 == s2) {
            System.out.println("s1 == s2");
        }

        if (s1.equals(s2)) {
            System.out.println("s1.equals(s2)");
        }
    }
}
    • A:s1 == s2
    • B:s1.equals(s2)
    • C:
s1 == s2
s1.equals(s2)
    • D:以上都不对

解析:

  • ==:用于比较基本数据类型的值是否相等或引用数据类型的引用地址是否相同
  • equals():默认会调用==,String和包装类覆写了该方法,用于比较引用数据类型的值是否相等


    image.png
  1. 以下关于StringBuffer类的代码的执行结果是( D )。(选择1项)
public class Test {
    public static void main(String args[]) {
        StringBuffer a = new StringBuffer("A");
        StringBuffer b = new StringBuffer("B");
        mb_operate(a, b);
        System.out.println(a + "." + b);
    }

    static void mb_operate(StringBuffer x, StringBuffer y) {
        x.append(y);
        y = x;
    }
}
    • A:A.B
    • B:A.A
    • C:AB.AB
    • D:AB.B

解析:
Java中只有值传递,引用数据类型的实参给形参传递的实际上是引用地址的副本。


image.png
  1. 给定如下Java代码,编译运行的结果是( C )。(选择1项)
public class Test {
    public static void main(String[] args) {
        String s1 = new String("pb_java_OOP_T5");
        String s2 = s1.substring(s1.lastIndexOf("_"));
        System.out.println("s2=" + s2);
    }
}
    • A:s2 = _java_OOP_T5
    • B:s2 = _OOP_T5
    • C:s2 = _T5
    • D:运行出错

解析:

  • lastIndexOf(String str):返回指定子字符串在此字符串中最右边出现处的索引
  • substring(int beginIndex):返回一个新的字符串,它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始,直到此字符串末尾

二、简答题

  1. 说明Error和Exception的区别。
    Error(错误)表示系统级的错误,是Java运行环境中的内部错误或者硬件故障,如内存资源不足等。对于这种错误,程序基本无能为力,除了退出运行外别无选择,它是由Java虚拟机抛出的。
    Exception(异常)表示需要捕获或者需要程序进行处理的异常,它处理的是因为程序设计的瑕疵而引起的问题或者因为外在输入等原因引起的一般性问题,是程序可以且必须处理的。
    Error与Exception都继承自Throwable类。
  2. 说明throws和throw的区别。


    image.png
  3. 为什么使用包装类及其作用?
    包装类即是把基本数据类型转换成引用数据类型。
    作用:
    1. 解决编码过程中只能接收对象的情况。如List中只能存入对象,不能存入基本数据类型
    2. 方便类型之间的转换。如String和int之间的转换可以通过int的包装类Integer来实现:int a = Integer.parseInt("123");
  4. 说明String、StringBuffer、StringBuilder区别与联系。


    image.png
  5. String str = "bjsxt";String str = new String("bjsxt");的区别。
    String str = "bjsxt";:先在字符串常量池中查找"bjsxt",若有则直接指向该字符串,若无则在字符串常量池中创建"bjsxt",然后再指向该字符串。最多会在字符串常量池中创建一个对象。
    String str = new String("bjsxt");:在堆中创建一个String对象,然后先在字符串常量池中查找"bjsxt",若有则直接指向该字符串,若无则在字符串常量池中创建"bjsxt",然后再指向该字符串。最多会在堆中创建一个对象、字符串常量池中创建一个对象。

三、编码题

  1. 编写程序接收用户输入的分数信息,如果分数在0100之间,输出成绩。如果成绩不在该范围内,抛出异常信息,提示分数必须在0100之间。
  • 代码:
package leif;

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double score = scanner.nextDouble();

        if (score >= 0 && score <= 100) {
            System.out.println(score);
            scanner.close();
        } else {
            try {
                throw new ScoreOutOfBoundsException("分数必须在0~100之间");
            } catch (ScoreOutOfBoundsException scoreOutOfBoundsException) {
                System.out.println(scoreOutOfBoundsException.getScoreOutOfBoundsExceptionMessage());
            } finally {
                scanner.close();
            }
        }
    }
}

class ScoreOutOfBoundsException extends Exception {
    private static final long serialVersionUID = 1L;
    private String scoreOutOfBoundsExceptionMessage;

    public ScoreOutOfBoundsException(String scoreOutOfBoundsExceptionMessage) {
        this.scoreOutOfBoundsExceptionMessage = scoreOutOfBoundsExceptionMessage;
    }

    public String getScoreOutOfBoundsExceptionMessage() {
        return scoreOutOfBoundsExceptionMessage;
    }

    public void setScoreOutOfBoundsExceptionMessage(String scoreOutOfBoundsExceptionMessage) {
        this.scoreOutOfBoundsExceptionMessage = scoreOutOfBoundsExceptionMessage;
    }
}
  • 结果截图:


    image.png
  1. 验证键盘输入的用户名不能为空、长度大于6、不能有数字。
  • 代码:
package leif;

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String username = scanner.nextLine();

        try {
            if (isLegal(username)) {
                System.out.println(username + "合法");
            }
        } catch (UsernameException usernameException) {
            System.out.println(usernameException.getUsernameExceptionMessage());
        }

        scanner.close();
    }

    public static boolean isLegal(String username) throws UsernameException {
        username = username.trim();

        if (username.length() == 0 || username == null) {
            throw new UsernameException("用户名不能为空");
        }

        if (username.length() <= 6) {
            throw new UsernameException("用户名长度应大于6");
        }

        if (username.matches(".*\\d+.*")) {
            throw new UsernameException("用户名不能有数字");
        }

        return true;
    }
}

class UsernameException extends Exception {
    private static final long serialVersionUID = 1L;
    private String usernameExceptionMessage;

    public UsernameException(String usernameExceptionMessage) {
        this.usernameExceptionMessage = usernameExceptionMessage;
    }

    public String getUsernameExceptionMessage() {
        return usernameExceptionMessage;
    }

    public void setUsernameExceptionMessage(String usernameExceptionMessage) {
        this.usernameExceptionMessage = usernameExceptionMessage;
    }
}
  • 结果截图:


    image.png
  1. 接收从键盘输入的字符串格式的年龄、分数、入学时间,转换为整数、浮点数、日期类型,并在控制台输出。
  • 代码:
package leif;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) throws ParseException {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入年龄:");
        String age = scanner.next();
        System.out.println(Integer.parseInt(age));
        System.out.print("请输入分数:");
        String score = scanner.next();
        System.out.println(Double.parseDouble(score));
        System.out.print("请输入入学时间:");
        String date = scanner.next();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(simpleDateFormat.format(simpleDateFormat.parse(date)));
        scanner.close();
    }
}
  • 结果截图:


    image.png
  1. 使用枚举模拟交通信号灯。
  • 代码:
package leif;

import java.text.ParseException;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) throws ParseException {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入颜色:");
        Color color = Color.getColor(scanner.next());

        switch (color) {
        case RED:
            System.out.println("红灯停");
            break;
        case GREEN:
            System.out.println("绿灯行");
            break;
        case YELLOW:
            System.out.println("黄灯眨着眼睛说:请你等一等");
            break;
        case NULL:
            System.out.println("输入错误!");
            break;
        }

        scanner.close();
    }
}

enum Color {
    RED("红"), GREEN("绿"), YELLOW("黄"), NULL;

    private String name;

    private Color() {
    }

    private Color(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    public static Color getColor(String name) {
        for (Color color : Color.values()) {
            if (name.equals(color.getName())) {
                return color;
            }
        }

        return NULL;
    }
}
  • 结果截图:


    image.png

四、程序题

  • 项目结构+README:


    image.png

    image.png

    image.png
  • 代码:
package dao;

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

import entity.Position;
import entity.Status;
import entity.employee.Architect;
import entity.employee.Designer;
import entity.employee.Employee;
import entity.employee.Programmer;
import entity.equipment.NoteBook;
import entity.equipment.PC;
import entity.equipment.Printer;

public class EmployeeDao {
    private static final List<Employee> EMPLOYEELIST;

    private EmployeeDao() {}

    static {
        EMPLOYEELIST = new ArrayList<Employee>();
        EMPLOYEELIST.add(new Employee("玄月", 23, 200000));
        EMPLOYEELIST.add(new Architect("沧月", 23, 100000, Position.ARCHITECT, Status.FREE, 50000, 50000, new NoteBook("戴尔", 7000)));
        EMPLOYEELIST.add(new Architect("彦", 25, 100000, Position.ARCHITECT, Status.FREE, 50000, 50000, new NoteBook("戴尔", 7000)));
        EMPLOYEELIST.add(new Designer("绘梨衣", 16, 100000, Position.DESIGNER, Status.VACATION, 50000, new Printer("佳能", "激光")));
        EMPLOYEELIST.add(new Designer("零", 14, 100000, Position.DESIGNER, Status.FREE, 50000, new Printer("佳能", "激光")));
        EMPLOYEELIST.add(new Designer("酒德麻衣", 20, 100000, Position.DESIGNER, Status.FREE, 50000, new Printer("佳能", "激光")));
        EMPLOYEELIST.add(new Designer("苏恩曦", 18, 100000, Position.DESIGNER, Status.FREE, 50000, new Printer("佳能", "激光")));
        EMPLOYEELIST.add(new Programmer("楚子航", 24, 50000, Position.PROGRAMMER, Status.FREE, new PC("戴尔", "三星17寸")));
        EMPLOYEELIST.add(new Programmer("雷姬", 16, 50000, Position.PROGRAMMER, Status.FREE, new PC("戴尔", "三星17寸")));
        EMPLOYEELIST.add(new Programmer("御坂美琴", 18, 50000, Position.PROGRAMMER, Status.FREE, new PC("戴尔", "三星17寸")));
        EMPLOYEELIST.add(new Programmer("薇尔莉特", 16, 50000, Position.PROGRAMMER, Status.FREE, new PC("戴尔", "三星17寸")));
    }

    public static List<Employee> getEmployeelist() {
        return EMPLOYEELIST;
    }
}
package dao;

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

import entity.Member;

public class MemberDao {
    private static final List<Member> MEMBERLIST = new ArrayList<Member>();
    private static int architectCounter = 0;
    private static int designerCounter = 0;
    private static int programmerCounter = 0;

    private MemberDao() {}

    public static List<Member> getMemberlist() {
        return MEMBERLIST;
    }

    public static int getArchitectCounter() {
        return architectCounter;
    }

    public static int getDesignerCounter() {
        return designerCounter;
    }

    public static int getProgrammerCounter() {
        return programmerCounter;
    }

    public static void architectCounterIncrement() {
        architectCounter++;
    }

    public static void architectCounterDecrement() {
        architectCounter--;
    }

    public static void designerCounterIncrement() {
        designerCounter++;
    }

    public static void designerCounterDecrement() {
        designerCounter--;
    }

    public static void programmerCounterIncrement() {
        programmerCounter++;
    }

    public static void programmerCounterDecrement() {
        programmerCounter--;
    }
}
package entity.employee;

import entity.Position;
import entity.Status;
import entity.equipment.Equipment;

public class Architect extends Employee {
    private Position position;
    private Status status;
    private double bonus;
    private int stock;
    private Equipment equipment;

    public Architect(String name, int age, double salary, Position position, Status status, double bonus, int stock, Equipment equipment) {
        super(name, age, salary);
        this.position = position;
        this.status = status;
        this.bonus = bonus;
        this.stock = stock;
        this.equipment = equipment;
    }

    public Position getPosition() {
        return position;
    }

    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    public double getBonus() {
        return bonus;
    }

    public int getStock() {
        return stock;
    }

    public Equipment getEquipment() {
        return equipment;
    }
}
package entity.employee;

import entity.Position;
import entity.Status;
import entity.equipment.Equipment;

public class Designer extends Employee {
    private Position position;
    private Status status;
    private double bonus;
    private Equipment equipment;

    public Designer(String name, int age, double salary, Position position, Status status, double bonus, Equipment equipment) {
        super(name, age, salary);
        this.position = position;
        this.status = status;
        this.bonus = bonus;
        this.equipment = equipment;
    }

    public Position getPosition() {
        return position;
    }

    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    public double getBonus() {
        return bonus;
    }

    public Equipment getEquipment() {
        return equipment;
    }
}
package entity.employee;

public class Employee {
    private static int idCounter = 1;
    private int id;
    private int memberId;
    private String name;
    private int age;
    private double salary;

    public Employee(String name, int age, double salary) {
        id = idCounter;
        this.name = name;
        this.age = age;
        this.salary = salary;
        idCounter++;
    }

    public static int getIdCounter() {
        return idCounter;
    }

    public int getId() {
        return id;
    }

    public int getMemberId() {
        return memberId;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public double getSalary() {
        return salary;
    }
}
package entity.employee;

import entity.Position;
import entity.Status;
import entity.equipment.Equipment;

public class Programmer extends Employee {
    private Position position;
    private Status status;
    private Equipment equipment;

    public Programmer(String name, int age, double salary, Position position, Status status, Equipment equipment) {
        super(name, age, salary);
        this.position = position;
        this.status = status;
        this.equipment = equipment;
    }

    public Position getPosition() {
        return position;
    }

    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    public Equipment getEquipment() {
        return equipment;
    }
}
package entity.equipment;

public interface Equipment {
    public abstract String getDescription();
}
package entity.equipment;

public class NoteBook implements Equipment {
    private String model;
    private double price;

    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;
    }

    @Override
    public String getDescription() {
        return model + "(" + price + ")";
    }
}
package entity.equipment;

public class PC implements Equipment {
    private String model;
    private String display;

    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;
    }

    @Override
    public String getDescription() {
        return model + "(" + display + ")";
    }
}
package entity.equipment;

public class Printer implements Equipment {
    private String model;
    private String type;

    public Printer(String model, String type) {
        this.model = model;
        this.type = type;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String getDescription() {
        return model + "(" + type + ")";
    }
}
package entity;

import entity.employee.Employee;

public class Member {
    private static int tIdCounter = 1;
    private int tId;
    private Employee employee;

    public Member(Employee employee) {
        tId = tIdCounter;
        this.employee = employee;
        tIdCounter++;
    }

    public int getTId() {
        return tId;
    }

    public Employee getEmployee() {
        return employee;
    }
}
package entity;

public enum Position {
    PROGRAMMER("程序员"), DESIGNER("设计师"), ARCHITECT("架构师");

    private String position;

    private Position(String position) {
        this.position = position;
    }

    public String getPosition() {
        return position;
    }
}
package entity;

public enum Status {
    FREE("空闲"), BUSY("工作"), VACATION("休假");

    private String status;

    private Status(String status) {
        this.status = status;
    }

    public String getStatus() {
        return status;
    }
}
package exception;

public class EmployeeException extends Exception {
    private static final long serialVersionUID = 1L;
    private String employeeExceptionMessage;

    public EmployeeException(String employeeExceptionMessage) {
        this.employeeExceptionMessage = employeeExceptionMessage;
    }

    public String getEmployeeExceptionMessage() {
        return employeeExceptionMessage;
    }

    public void setEmployeeExceptionMessage(String employeeExceptionMessage) {
        this.employeeExceptionMessage = employeeExceptionMessage;
    }
}
package exception;

public class MemberException extends Exception {
    private static final long serialVersionUID = 1L;
    private String memberExceptionMessage;

    public MemberException(String memberExceptionMessage) {
        this.memberExceptionMessage = memberExceptionMessage;
    }

    public String getMemberExceptionMessage() {
        return memberExceptionMessage;
    }

    public void setMemberExceptionMessage(String memberExceptionMessage) {
        this.memberExceptionMessage = memberExceptionMessage;
    }
}
package service.impl;

import java.util.List;

import dao.EmployeeDao;
import entity.employee.Employee;
import exception.EmployeeException;
import service.EmployeeService;

public class EmployeeServiceImpl implements EmployeeService {
    private EmployeeServiceImpl() {}

    private static volatile EmployeeServiceImpl employeeServiceImpl = null;

    public static EmployeeServiceImpl getInstance() {
        if (employeeServiceImpl == null) {
            synchronized (EmployeeServiceImpl.class) {
                if (employeeServiceImpl == null) {
                    employeeServiceImpl = new EmployeeServiceImpl();
                }
            }
        }

        return employeeServiceImpl;
    }

    @Override
    public List<Employee> findAll() {
        return EmployeeDao.getEmployeelist();
    }

    @Override
    public Employee findById(int id) throws EmployeeException {
        for (Employee employee : findAll()) {
            if (id == employee.getId()) {
                return employee;
            }
        }

        throw new EmployeeException("查无此人!");
    }
}
package service.impl;

import java.util.List;

import dao.MemberDao;
import entity.Member;
import entity.Status;
import entity.employee.Architect;
import entity.employee.Designer;
import entity.employee.Employee;
import entity.employee.Programmer;
import exception.EmployeeException;
import exception.MemberException;
import service.MemberService;

public class MemberServiceImpl implements MemberService {
    private MemberServiceImpl() {}

    private static volatile MemberServiceImpl employeeServiceImpl = null;

    public static MemberServiceImpl getInstance() {
        if (employeeServiceImpl == null) {
            synchronized (MemberServiceImpl.class) {
                if (employeeServiceImpl == null) {
                    employeeServiceImpl = new MemberServiceImpl();
                }
            }
        }

        return employeeServiceImpl;
    }

    @Override
    public void createById(int id) throws MemberException {
        Employee employee;

        try {
            employee = EmployeeServiceImpl.getInstance().findById(id);
        } catch (EmployeeException employeeException) {
            throw new MemberException(employeeException.getEmployeeExceptionMessage());
        }

        if (employee instanceof Architect) {
            if (MemberDao.getArchitectCounter() >= 1) {
                throw new MemberException("团队中只能有一名架构师,成员已满,无法添加");
            }

            Architect architect = (Architect)employee;

            if (Status.BUSY == architect.getStatus()) {
                throw new MemberException("该员工已是团队成员");
            }

            if (Status.VACATION == architect.getStatus()) {
                throw new MemberException("该员工正在休假,无法添加");
            }

            architect.setStatus(Status.BUSY);
            MemberDao.architectCounterIncrement();
        } else if (employee instanceof Designer) {
            if (MemberDao.getDesignerCounter() >= 2) {
                throw new MemberException("团队中只能有两名设计师,成员已满,无法添加");
            }

            Designer designer = (Designer)employee;

            if (Status.BUSY == designer.getStatus()) {
                throw new MemberException("该员工已是团队成员");
            }

            if (Status.VACATION == designer.getStatus()) {
                throw new MemberException("该员工正在休假,无法添加");
            }

            designer.setStatus(Status.BUSY);
            MemberDao.designerCounterIncrement();
        } else if (employee instanceof Programmer) {
            if (MemberDao.getProgrammerCounter() >= 3) {
                throw new MemberException("团队中只能有三名程序员,成员已满,无法添加");
            }

            Programmer programmer = (Programmer)employee;

            if (Status.BUSY == programmer.getStatus()) {
                throw new MemberException("该员工已是团队成员");
            }

            if (Status.VACATION == programmer.getStatus()) {
                throw new MemberException("该员工正在休假,无法添加");
            }

            programmer.setStatus(Status.BUSY);
            MemberDao.programmerCounterIncrement();
        } else {
            throw new MemberException("该员工不是开发人员,无法添加");
        }

        Member member = new Member(employee);
        MemberDao.getMemberlist().add(member);
    }

    @Override
    public void removeById(int tId) throws MemberException {
        Member member;

        try {
            member = findByTId(tId);
        } catch (MemberException memberException) {
            throw new MemberException(memberException.getMemberExceptionMessage());
        }

        MemberDao.getMemberlist().remove(member);
        Employee employee = member.getEmployee();

        if (employee instanceof Architect) {
            ((Architect)employee).setStatus(Status.FREE);
            MemberDao.architectCounterDecrement();
        } else if (employee instanceof Designer) {
            ((Designer)employee).setStatus(Status.FREE);
            MemberDao.designerCounterDecrement();
        } else if (employee instanceof Programmer) {
            ((Programmer)employee).setStatus(Status.FREE);
            MemberDao.programmerCounterDecrement();
        }
    }

    @Override
    public List<Member> findAll() {
        return MemberDao.getMemberlist();
    }

    @Override
    public Member findByTId(int tId) throws MemberException {
        for (Member member : findAll()) {
            if (tId == member.getTId()) {
                return member;
            }
        }

        throw new MemberException("查无此人!");
    }
}
package service;

import java.util.List;

import entity.employee.Employee;
import exception.EmployeeException;

public interface EmployeeService {
    public abstract List<Employee> findAll();

    public abstract Employee findById(int id) throws EmployeeException;
}
package service;

import java.util.List;

import entity.Member;
import exception.MemberException;

public interface MemberService {
    public abstract void createById(int id) throws MemberException;

    public abstract void removeById(int tId) throws MemberException;

    public abstract List<Member> findAll();

    public abstract Member findByTId(int tId) throws MemberException;
}
package test;

import java.util.Scanner;

import entity.Member;
import entity.employee.Architect;
import entity.employee.Designer;
import entity.employee.Employee;
import entity.employee.Programmer;
import exception.MemberException;
import service.EmployeeService;
import service.MemberService;
import service.impl.EmployeeServiceImpl;
import service.impl.MemberServiceImpl;
import util.TestUtil;

public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        EmployeeService employeeService = EmployeeServiceImpl.getInstance();
        MemberService memberService = MemberServiceImpl.getInstance();

        label: while (true) {
            System.out.println("------------------------------开发团队调度软件------------------------------");
            System.out.println("ID\t姓名\t年龄\t工资\t\t职位\t状态\t奖金\t股票\t领用设备");

            for (Employee employee : employeeService.findAll()) {
                System.out.print(employee.getId() + "\t" + employee.getName() + "\t" + employee.getAge() + "\t" + employee.getSalary() + "\t");

                if (employee instanceof Architect) {
                    Architect architect = (Architect)employee;
                    System.out.print(architect.getPosition().getPosition() + "\t" + architect.getStatus().getStatus() + "\t" + architect.getBonus() + "\t" + architect.getStock() + "\t" + architect.getEquipment().getDescription());
                } else if (employee instanceof Designer) {
                    Designer designer = (Designer)employee;
                    System.out.print(designer.getPosition().getPosition() + "\t" + designer.getStatus().getStatus() + "\t" + designer.getBonus() + "\t\t" + designer.getEquipment().getDescription());
                } else if (employee instanceof Programmer) {
                    Programmer programmer = (Programmer)employee;
                    System.out.print("\t" + programmer.getPosition().getPosition() + "\t" + programmer.getStatus().getStatus() + "\t\t\t" + programmer.getEquipment().getDescription());
                }

                System.out.println();
            }

            System.out.println("--------------------------------------------------------------------------------");
            System.out.print("1-团队列表 2-添加团队成员 3-删除团队成员 4-退出 请选择(1-4):");

            switch (scanner.nextInt()) {
                case 1:
                    System.out.println("------------------------------团队成员列表------------------------------");
                    System.out.println("TID/ID\t姓名\t年龄\t工资\t\t职位\t奖金\t股票");

                    for (Member member : memberService.findAll()) {
                        Employee employee = member.getEmployee();
                        System.out.print(member.getTId() + "/" + employee.getId() + "\t" + employee.getName() + "\t" + employee.getAge() + "\t" + employee.getSalary() + "\t");

                        if (employee instanceof Architect) {
                            Architect architect = (Architect)employee;
                            System.out.print(architect.getPosition().getPosition() + "\t" + architect.getBonus() + "\t" + architect.getStock());
                        } else if (employee instanceof Designer) {
                            Designer designer = (Designer)employee;
                            System.out.print(designer.getPosition().getPosition() + "\t" + designer.getBonus());
                        } else if (employee instanceof Programmer) {
                            Programmer programmer = (Programmer)employee;
                            System.out.print("\t" + programmer.getPosition().getPosition());
                        }

                        System.out.println();
                    }

                    System.out.println("--------------------------------------------------------------------------------");
                    break;
                case 2:
                    System.out.println("------------------------------添加成员------------------------------");
                    System.out.print("请输入要添加的员工的ID:");

                    try {
                        memberService.createById(scanner.nextInt());
                        System.out.println("添加成功");
                        TestUtil.pressEnterToContinue(scanner);
                    } catch (MemberException memberException) {
                        System.out.println(memberException.getMemberExceptionMessage());
                    }

                    break;
                case 3:
                    System.out.println("------------------------------删除成员------------------------------");
                    System.out.print("请输入要删除的员工的TID:");
                    int tId = scanner.nextInt();

                    try {
                        memberService.findByTId(tId);
                        System.out.print("确认是否删除(Y/N):");

                        while (true) {
                            String isConfirmed = scanner.next();

                            if ("Y".equals(isConfirmed.toUpperCase())) {
                                memberService.removeById(tId);
                                System.out.println("删除成功");
                                TestUtil.pressEnterToContinue(scanner);
                                break;
                            } else if ("N".equals(isConfirmed.toUpperCase())) {
                                break;
                            } else {
                                System.out.print("输入错误!确认是否删除(Y/N):");
                            }
                        }
                    } catch (MemberException memberException) {
                        System.out.println(memberException.getMemberExceptionMessage());
                    }

                    break;
                case 4:
                    break label;
                default:
                    System.out.println("输入错误!");
                    break;
            }
        }

        scanner.close();
    }
}
package util;

import java.util.Scanner;

public class TestUtil {
    private TestUtil() {}

    public static void pressEnterToContinue(Scanner scanner) {
        System.out.println("按回车键继续...");
        scanner.nextLine();

        while (true) {
            String enter = scanner.nextLine();

            if ("".equals(enter)) {
                break;
            }

            System.out.println("输入错误!按回车键继续...");
        }
    }
}
  • 结果截图:


    image.png

    image.png

    image.png

    image.png

    image.png

    image.png

    image.png

    image.png

    image.png

    image.png

    image.png

    image.png

    image.png

    image.png

    image.png

    image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,907评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,987评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,298评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,586评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,633评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,488评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,275评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,176评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,619评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,819评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,932评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,655评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,265评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,871评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,994评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,095评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,884评论 2 354

推荐阅读更多精彩内容