从布尔方法返回字符串

用户名

我有下面的类图。

在此处输入图片说明

我需要输出一个类似于“ James,Sid(1234):导演为£100000.0(含税£29822.0)且有资格获得奖金的toString

但是我找不到一种方法可以打印出返回的部分,无论雇员是否有资格获得奖金。

任何帮助深表感谢!

这是我尝试创建类的尝试。

package org.com1027.formative.ye00036;

public class Employee {
    //Class Field(s)
    private int id = 0;
    private String forename = null;
    private String surname = null;
    private Salary salary = null;
    private CompanyPosition companyPosition = null;

    //Parameterised constructor using all fields, allowing creation of objects
    public Employee(int id, String forename, String surname, Salary salary, CompanyPosition companyPosition) {
        super();
        this.id = id;
        this.forename = forename;
        this.surname = surname;
        this.salary = salary;
        this.companyPosition = companyPosition;
    }

    //Getters-Accessors
    //Returns the employee's ID
    public int getId() {
        return id;
    }
    //Returns the employee's Forename
    public String getForename() {
        return forename;
    }
    //Returns the employee's Surname
    public String getSurname() {
        return surname;
    }
    //Returns the employee's Salary
    public Salary getSalary() {
        return salary;
    }
    //Returns the employee's Company Position
    public CompanyPosition getPositionName() {
        return companyPosition;
    }
    //Checks if an employee is eligible for bonus
    public boolean eligibleForBonus(){
        if (salary.getSalary() >= 40000) 
            return true;
        else 
            return false;
    }

    @Override
    public String toString() {
        return getForename() + ", " + getSurname() + "(" + getId() +
                "): " + getPositionName() + "at " + salary.getSalary() + " (" + salary.calculateTax() + ") and is ";
    }

}
幸运狗32

我建议您只更改toString方法,使其具有符合条件的条件:

        return getForename() + ", " + getSurname() + "(" + getId() +
            "): " + getPositionName() + "at " + salary.getSalary() + " (" + salary.calculateTax() + ") and is "
            + (eligibleForBonus()? "eligible for a bonus" : "not eligible for a bonus");

您还可以在toString方法中使用更复杂的逻辑,它们不必立即返回:

    @Override
public String toString() {
    String returnString = getForename() + ", " + getSurname() + "(" + getId() +
            "): " + getPositionName() + "at " + salary.getSalary() + " (" + salary.calculateTax() + ") and is ";

    if(eligibleForBonus()){
        returnString += "eligible for bonus.";
    }else{
        returnString += "not eligible for bonus.";
    }

    return returnString;

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章