上的变量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\"");
}
答案 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语句之后添加了它。