public class FooCorporation {
public static void main(String[] args) {
System.out.println("Employee 1:");
payment(7.5,35);
System.out.println("Employee 2:");
payment(8.2, 47);
System.out.println("Employee 3:");
payment(10.00,73);
}
public static void payment(double basePay, int hours) {
if(basePay<8. || hours >60) {
System.out.println("ERORR; base pay less than 8.00$ or hours worked greater than 60.");
}
else if(hours<=40) {
System.out.println("Total pay = " + hours*basePay + "$");
}
else if(hours>40) {
int count = hours-40;
System.out.println("Total pay = " + (hours-count)*basePay+(1.5*basePay*count)+ "$");
}
}
}
为什么员工2的输出错误?
GIVEN : BasePay HoursWorked
Employee 1 $7.50 35
Employee 2 $8.20 47
Employee 3 $10.00 73
答案 0 :(得分:0)
当你在这里打印时:
System.out.println("Total pay = " + (hours-count)*basePay+(1.5*basePay*count)+ "$");
您正在连接2个数字((hours-count)*basePay
和(1.5*basePay*count)
),而不是以数学方式添加它们。您需要将其替换为(在括号中添加数字):
System.out.println("Total pay = " + ((hours - count) * basePay + (1.5 * basePay * count)) + "$");
原因是首先评估"Total pay = " + (hours-count)*basePay
,并将表达式(hours-count)*basePay
的结果连接到字符串Total pay =
。接下来,此连接的结果与表达式(1.5 * basePay * count)
的结果连接在一起。由于您不需要这个,并且您希望在连接之前先评估两个表达式,因此需要用括号括起它们以使其优先。
答案 1 :(得分:0)
使用 System.out.println(“总薪水=”+((小时数)* basePay +(1.5 * basePay * count)));
需要添加大括号,以便JVM知道需要处理语句的顺序