我创建了一个生成薪资存根的目标问题。该程序不会生成任何常规的薪酬输出,而只是说" $ 0.00"。无法解决问题。
预计:"正常时间:40注册率:$ 15.50 Reg Pay: $ 620.00"
我的代码:"正常时间:40 Reg Reg:$ 15.50 Reg 支付:0.00美元"
我试图重新格式化,但我仍然遇到此错误。
public class Activity2PayStub {
public static final double OVERTIME_FACTOR = 1.5;
public static final double FEDERAL_FACTOR = 0.2;
public static final double SOCIAL_FACTOR = 0.1;
private String employeeName;
private String employeeSSN;
private int regularH;
private int overtimeH;
private double payrateH;
private double regularPay = (regularH * payrateH);
private double overtimePR = payrateH * (OVERTIME_FACTOR);
private double overtimePay = overtimePR * overtimeH;
private double grossPay = regularPay + overtimePay;
private double ssTax = grossPay * (SOCIAL_FACTOR);
private double federalTax = (grossPay - ssTax) * (FEDERAL_FACTOR);
private double netPay = grossPay - (federalTax + ssTax);
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Activity2PayStub a2ps = new Activity2PayStub();
a2ps.getInput(keyboard);
a2ps.calculate();
a2ps.printPayStub();
}
/** @param keyboard command-line arguments. */
public void getInput(Scanner keyboard) {
System.out.print("Enter employee name: ");
employeeName = keyboard.nextLine();
System.out.print("Enter employee SNN (incl. hyphens: ");
employeeSSN = keyboard.nextLine();
System.out.print("Enter number of regular hours worked: ");
regularH = keyboard.nextInt();
System.out.print("Enter number of overtime hours worked: ");
overtimeH = keyboard.nextInt();
System.out.print("Enter hourly pay rate : ");
payrateH = keyboard.nextDouble();
}
public void calculate() {
}
/** simply prints. */
public void printPayStub() {
Scanner input = new Scanner(System.in);
System.out.println("_______________________"
+ "_____________________________________________");
String format = "Name: %-37s SSN: %-11s\n";
System.out.printf(format, employeeName, employeeSSN);
format = "Regular Hours: %-8d Reg Rate: $%-8.2f Reg Pay: $%-8.2f\n";
System.out.printf(format, regularH, payrateH, regularPay);
format = "Overtime Hours: %-8dOT Rate: $%-8.2f OT Pay: $%-8.2f\n";
System.out.printf(format, overtimeH, overtimePR, overtimePay);
format = "Gross Pay: $%-8.2f\n";
System.out.printf(format, grossPay);
format = "SS Withholding: $%-8.2f\n";
System.out.printf(format, ssTax);
format = "Federal Tax: $%-8.2f\n";
System.out.printf(format, federalTax);
format = "Net Pay: $%-8.2f\n";
System.out.printf(format, netPay);
System.out.println("________________________"
+ "__________________________________________");
}
}
答案 0 :(得分:7)
这是因为计算是在实例创建时执行的。您应该将计算移动到calculate()
方法。
JLS chapter 8.3.2证实了这一点:
如果声明符用于实例变量(即非静态字段),则会计算变量初始值设定项,并在每次创建类的实例时执行赋值