我該如何編寫一個toString()方法,用於爲三名員工打印姓名和computePay以及兩位小數位?在我添加StringBuilder之前,該程序正在工作(打印名稱和星期付款到命令行)。任何幫助表示讚賞。如何編寫toString()方法
import javax.swing.JOptionPane;
public class TestPayroll {
public static void main(String[] args) {
Payroll employee1 = new Payroll("Tiny Tim", 100.25, 40);
Payroll employee2 = new Payroll("Brad Pitt", 150.50, 10);
Payroll employee3 = new Payroll("Madonna", 124.24, 20);
StringBuilder sb = new StringBuilder();
String toDisplay=sb.toString();
sb.append(String.format("\n", employee1.getName(), employee1.getComputePay()));
sb.append(String.format("\n", employee2.getName(), employee2.getComputePay()));
JOptionPane.showMessageDialog(null, sb.toString(), toDisplay, JOptionPane.INFORMATION_MESSAGE);
}
}
public class Payroll {
public static void main(String[] args) {
}
private String name;
private double payRate;
private double hrsWorked;
private double computePay;
//default constructor
public Payroll() {
this.name = name;
this.payRate = payRate;
this.hrsWorked = hrsWorked;
this.computePay = computePay;
}
//Payroll constructor
public Payroll(String name, double payRate, double hrsWorked) {
this.name = name;
this.payRate = payRate;
this.hrsWorked = hrsWorked;
}
//return name
public String getName() {
return name;
}
//set name
public void setName(String name) {
this.name = name;
}
//return pay rate
public double getPayRate() {
return payRate;
}
//set pay rate
public void setPayRate(double payRate) {
this.payRate = payRate;
}
//return hours worked for the week
public double getHrsWorked() {
return hrsWorked;
}
//set hours worked for the week
public void setHrsWorked(double hrsWorked) {
this.hrsWorked = hrsWorked;
}
//find week's pay
public double getComputePay() {
double computePay = payRate * hrsWorked;
return computePay;
}
}
*爲三位僱員保留2位小數* *我不明白這行可以解釋更多! – Azad
你的TestPayroll類甚至不會按原樣編譯。請修正主方法的'}' – Multithreader
抱歉。有3名員工,我想顯示他們的姓名和週薪。 weeksPay應該有2個小數位。 – Grafica