-1

变量 netPay on

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\"");
}
4

3 回答 3

1

想象一下,weeklyTime它小于 40(举例来说,假设为 20)。

netPay是在范围内,但块if (weeklyTime>40)else if (weeklyTime==40)块都不会初始化它。该else块将运行,它根本不初始化netPay。您将需要修改 else 块以提供netPay值。我对计算净工资的规则知之甚少,不知道你想在这个 else 块中使用什么公式(weeklyTime < 40 是输入它的(隐式)条件)

于 2014-09-23T00:10:56.783 回答
0

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

您可以做的是在您声明它的那一刻对其进行初始化,例如:

double netPay = 0;

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

else {
    overTimehours = 0;
    overTime = 0;
    netPay = 0;
}
于 2014-09-23T00:23:27.740 回答
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 语句之后添加了它。

于 2014-09-23T03:34:15.080 回答