如何找到工作时间最少的员工并显示他们的姓名和工作总时数?
我似乎无法弄清楚如何显示名称(即员工2,员工3等),最少工作小时数总是等于零。
import javax.swing.JOptionPane;
public class EmpHrsWrkd {
public static void main(String[] args) {
String[] employees =
{
"Employee 1",
"Employee 2",
"Employee 3",
"Employee 4",
"Employee 5",
"Employee 6",
};
int[][] hrsWrkd =
{
{ 5, 8, 6, 2 },
{ 2, 0, 8, 6 },
{ 6, 4, 9, 5 },
{ 7, 8, 8, 4 },
{ 3, 6, 2, 8 },
{ 9, 5, 1, 7 },
};
// Calculate the rows and columns in 2D array
final int EMPLOYEES = hrsWrkd.length;
final int HOURS = hrsWrkd[0].length;
// Find employee that worked least number of hours
int min = hrsWrkd[0][0];
for (int col = 0; col < hrsWrkd.length; col++) {
for (int row = 0; row < hrsWrkd[col].length; row++) {
if (min > hrsWrkd[col][row]) {
min = hrsWrkd[col][row];
}
}
}
JOptionPane.showMessageDialog(null, min);
}
}
答案 0 :(得分:1)
因此,在您的代码中,您要比较每个员工的单个小时而不是它的总和。它始终为0,因为矩阵中的最小数字是0.
要做到这一点,首先必须为每位员工计算小时数,然后将其进行比较以获得验证结果。如下图所示:
int minValue = Integer.MAX_VALUE;
int employeeWithMinValue = -1;
for (int col = 0; col < hrsWrkd.length; col++) {
int tempSum = 0;
for (int row = 0; row < hrsWrkd[col].length; row++) {
tempSum = tempSum + hrsWrkd[col][row];
}
if (tempSum < minValue) {
minValue = tempSum;
employeeWithMinValue = col;
}
}
JOptionPane.showMessageDialog(null, "Employee number " + employeeWithMinValue +
" worked only " + minValue + " hours");
希望它有所帮助!