我将如何编写一个 toString() 方法,为三个员工打印名称和 computePay,小数点后 2 位?在我添加 StringBuilder 之前,该程序正在运行(将名称和 weekPay 打印到命令行)。任何帮助表示赞赏。
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;
}
}