Java输出不能像我希望的那样工作

时间:2015-12-17 14:24:36

标签: java

public class FooCorporation {
    public int hoursWorked;
    public double basePay;
    double salary;

    public FooCorporation (int a, double b) {
        a= hoursWorked;
        b = basePay;
    }

    void mySalary(){
        if (hoursWorked>40){
            salary = 40*basePay + ((hoursWorked - 40)*basePay*1.5);
            System.out.println(salary);
        } else {
            salary = hoursWorked*basePay ;
            System.out.println(salary);
        }
    }
}

public class SalaryTest {
    public static void main(String[] args) {
        FooCorporation employee1 = new FooCorporation(4, 7.5);
        FooCorporation employee2 = new FooCorporation(47, 8.2);
        FooCorporation employee3 = new FooCorporation(59, 10);

        employee1.mySalary();
        employee2.mySalary();
        employee3.mySalary();
    }
}

此代码的输出始终为0.0,并且无法理解原因。我在想,也许构造函数不工作或者工资加倍存在某种问题。如果有人能看到它会很酷..谢谢

2 个答案:

答案 0 :(得分:7)

你在这里犯了错误:

  public FooCorporation (int a, double b) {
     a= hoursWorked;
     b = basePay;
     }

尝试在构造函数中为变量赋值,如下所示:

  public FooCorporation (int a, double b) {
     this.hoursWorked = a;
     this.basePay = b;
    }

答案 1 :(得分:5)

您的构造函数分配已回到前面

public FooCorporation (int a, double b) {
         a= hoursWorked;
         b = basePay;
        }

应该是

public FooCorporation (int a, double b) {
         hoursWorked = a;
         basePay = b;
        }