变量netPay一直说它没有初始化

时间:2014-09-23 00:09:11

标签: java revenue

上的变量netPay
System.out.println("\t Regular Pay for 40.0 hour(s): $" + netPay);

一直说它没有初始化。它唯一有效的时间是我采用if-else语句。

public static void main(String [] args){
    int employeeNumber;
    double hourlySalary, weeklyTime, netPay, overTime, overTimehours;

    Scanner keyboard= new Scanner(System.in);
    System.out.println("Welcome to \"TEMPLE HUMAN RESOURCES\"");
    System.out.println();
    System.out.print("\t Enter Employee Number: ");
    employeeNumber=keyboard.nextInt();
    System.out.print("\t Enter Hourly Salary: ");
    hourlySalary=keyboard.nextDouble();
    System.out.print("\t Enter Weekly Time: ");
    weeklyTime=keyboard.nextDouble();
    System.out.println();

    overTimehours=weeklyTime-40;
    overTime=(1.5*10)*hourlySalary;

    if (weeklyTime>40) {
        netPay=(weeklyTime*hourlySalary)+(overTime*overTimehours);
    }else if (weeklyTime==40){
        netPay=40*hourlySalary;
    }else {
        overTimehours=0;
        overTime=0;
    }

    System.out.println("\t Employee #: " + employeeNumber);
    System.out.println("\t Hourly Salary: $" + hourlySalary);
    System.out.println("\t Weekly Time: " + weeklyTime + " hour(s)");
    System.out.println("\t Regular Pay for 40.0 hour(s): $" + netPay);
    System.out.println("\t Overtime Pay for " +overTimehours+ " hour(s): $" + overTime);
    System.out.println("\t Net Pay: $" + (overTime+ netPay));
    System.out.println();
    System.out.println("Thank you for using \"Temple Human Resources\"");
}

3 个答案:

答案 0 :(得分:1)

想象一下weeklyTime小于40(为了举个例子,让我们说20)。

netPay在范围内,但if (weeklyTime>40)else if (weeklyTime==40)块都不会用于初始化它。 else块将运行,根本不会初始化netPay。您需要修改else块以给netPay一个值。我不太了解计算净工资的规则,知道你要在这个其他区块中使用什么公式(weeklyTime< 40是输入它的(隐含)条件)

答案 1 :(得分:0)

是的,因为netPay仅在前两个if块中初始化。如果不满足这些条件怎么办?由于您在声明它时未初始化其值,并且您也没有在else中设置它,因此在这种情况下它没有初始化。

你能做的就是在宣布它的那一刻初始化它,例如:

double netPay = 0;

或将其设置在else块中,例如:

else {
    overTimehours = 0;
    overTime = 0;
    netPay = 0;
}

答案 2 :(得分:0)

我明白了,这就是我的所作所为。

//if there's an overtime or no overtime
if (weeklyTime>40) {
    netPay=(40*hourlySalary)+(overTime*overTimehours);

}
else if (weeklyTime==40){
    netPay=40*hourlySalary;
}
else {
    overTimehours=0;
    overTime=0;

}
//Pay without overtime
    netPay=(weeklyTime-overTimehours)*hourlySalary;

我刚刚在if-else语句之后添加了它。