我正在学习麻省理工学院的一门旧课程,试图在业余时间学习Java。这个早期的任务是关于计算加班费。我如何生成组合每个员工的输出的输出,以便获得如下输出:
员工 1 的工资为 262.5 美元,但工资低于最低工资 7.5
美元 员工 3 工作 73.0 小时,超过法定限制,获得 895.0 美元的报酬
public class FooCorporation {
public static void main(String[] arguments) {
double[] basePay = { 7.50, 8.20, 10.00 };
double[] hoursWorked = { 35, 47, 73 };
double[] totalPay = new double[basePay.length];
String[] Employee = { "Employee 1", "Employee 2", "Employee 3" };
{
for (int x = 0; x < basePay.length; x++) {
if (basePay[x] < 8.0) {
System.out.println(Employee[x] + " gets paid below the minimum wage at $" + basePay[x]);
}
if (hoursWorked[x] > 60) {
System.out.println(Employee[x] + " works " + hoursWorked[x] + " hours which is over the legal limit" );
}
if (hoursWorked[x] > 40) {
totalPay[x] = (40.0 * basePay[x]) + ((hoursWorked[x] - 40.0) * (basePay[x] * 1.5));
} else if (hoursWorked[x] < 40.0)
totalPay[x] = hoursWorked[x] * basePay[x];
System.out.println(Employee[x] + " gets paid $" + totalPay[x]);
}
}
}
}
列出所有情况和条件:
将所有单个数据放在简单变量中:
double pay = basePay[x];
为此,我建议对数组使用复数形式,对元素使用单数。
从标准开始:
boolean underpaid = pay < 8.0;
boolean overworked = hoursWorked[x] > 60;
...
然后结合这些标准(if (underpaid && overworked)
),确保您涵盖所有情况,然后使用格式化打印。
if (...) {
System.out.printf("%s gets paid $%.2f but"
+ " gets paid below the minimum wage at $%f%n", employee, pay, min);
} else if (...) {
System.out.printf("%s works %.1f hours which is over the legal limit"
+ " and gets paid $%.2f%n", employee, hours, pay);
}
此代码将输出类似于您要查找的内容,您必须在最低工资和过度工作报表之前输出总工资,反之亦然。您不能对员工 1 使用一种方式,对员工 3 使用另一种方式。
要合并输出,请使用 print 语句而不是 println 作为总付薪输出。这不会在输出后创建新行,因此将其与后续的打印语句合并。
public class FooCorporation {
public static void main(String[] arguments) {
double[] basePay = { 7.50, 8.20, 10.00 };
double[] hoursWorked = { 35, 47, 73 };
double[] totalPay = new double[basePay.length];
String[] Employee = { "Employee 1", "Employee 2", "Employee 3" };
for (int x = 0; x < basePay.length; x++) {
if (hoursWorked[x] > 40) {
totalPay[x] = (40.0 * basePay[x]) + ((hoursWorked[x] - 40.0) * (basePay[x] * 1.5));
} else if (hoursWorked[x] < 40.0)
totalPay[x] = hoursWorked[x] * basePay[x];
System.out.print("Employee[x] + " gets paid $" + totalPay[x]);
if (basePay[x] < 8.0) {
System.out.println(" but gets paid below the minimum wage at $" + basePay[x]);
}
if (hoursWorked[x] > 60) {
System.out.println(Employee[x] + " but works " + hoursWorked[x] + " hours which is over the legal limit" );
}
}
}
}