[英]Return string from boolean method
我有以下類圖。
我需要輸出一個類似於“James, Sid (1234): Director at £100000.0 (£29822.0 tax) and arequalified for bonus ”的 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 ";
}
}
您可以在此處使用三元運算符。
在你的toString
方法中,聲明一個String
類型的變量,並根據薪水是否大於40,000
設置這個變量的值。 然后在返回的String
末尾附加此變量的值。
這是你可以做到的方法
@Override
public String toString() {
String val = (eligibleForBonus()) ? "eligible for bonus" : "not eligible for bonus";
return getForename() + ", " + getSurname() + "(" + getId() +
"): " + getPositionName() + "at " + salary.getSalary() + " (" + salary.calculateTax() + ") and is "+val;
}
我建議只更改您的 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.