在get set语句中抛出并捕获

时间:2017-10-25 23:16:33

标签: java

我有一个主班和一个员工班。我的目标是第二次测试返回“工资不能为负”,因为每小时输入率为-20。相反,它使得总收入为负。我该怎么办?我觉得我的问题是在throw catch语句中的某个地方。没有错误,但它没有显示我的引用。

package employee;

public class Main {

    public static void main(String[] args) {

        Employee ryan = new Employee("Ryan", "Smith", 40, 20);

        System.out.println("Test #1");
        System.out.println(ryan.getFirstName() + " " + ryan.getLastName() + ", worked " + ryan.getHoursWorked() + " hours and earned $"
                + ryan.getHoursWorked() * ryan.getWage());

        Employee hayden = new Employee("Hayden", "Moore", 20, -10);

        System.out.println("Test #2");
        System.out.println(hayden.getFirstName() + " " + hayden.getLastName() + ", worked " + hayden.getHoursWorked() + " hours and earned $"
                + hayden.getHoursWorked() * hayden.getWage());
    }
}

package employee;

public class Employee {
    private String firstName, lastName;
    int hoursWorked, wage;

    public Employee(String firstName, String lastName, int hoursWorked, int wage) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.hoursWorked = hoursWorked;
        this.wage = wage;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public void setHoursWorked(int hoursWorked) {
        this.hoursWorked = hoursWorked;
    }

    public int getHoursWorked() {
        return hoursWorked;
    }

    public void setWage(int wage) {
        if (wage < 0) {
            try {
                throw new Exception("Wage cannot be negative");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else
            this.wage = wage;
    }

    public int getWage() {
        return wage;
    }
}

2 个答案:

答案 0 :(得分:0)

你可以在这里考虑两个选项,你可以将异常的逻辑放在构造函数中,或者你可以创建一个没有用于检查异常的参数的构造函数,并在实例后使用getter和setter物体。我不建议在构造函数中使用setter,如果你这样做,逻辑就会变得有点模糊,但它也是你可以做的事情

答案 1 :(得分:0)

您没有通过构造函数中的setter,而是直接分配传递的值,将构造函数更改为:

public Employee(String firstName, String lastName, int hoursWorked, int wage) {
    setFirstName(firstName);
    setLastName(lastName);
    setHoursWorked(hoursWorked);
    setWage(wage);
}

这样,每个参数都必须通过setter。