我有一个主要班级和一个雇员班级。我的目标是第二次测试返回“工资不能为负”,原因是每小时的输入率为-20。相反,它使赚取的美元总额变为负数。我要解决什么?我觉得我的问题出在罚球声明中。没有错误,但没有显示我的报价。

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

最佳答案

我想您可以在这里有两个选择,可以将异常的逻辑或放入构造函数中,也可以创建不带用于检查异常的参数的构造函数,并在实例对象之后使用getter和setter代替。我不建议在构造函数中使用二传手,如果这样做,逻辑会变得有些晦涩,但是您也可以这样做

关于java - 抛出并捕获get set语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46943453/

10-10 23:12