gpt4 book ai didi

java - 如何找到最小的行总数并在二维数组中显示相应的名称

转载 作者:行者123 更新时间:2023-12-01 11:19:55 25 4
gpt4 key购买 nike

如何找到工作时间最少的员工并显示他们的姓名和总工作时间?

我似乎不知道如何显示姓名(即员工 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,因为矩阵中的最小数字是 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");

希望对你有帮助!

关于java - 如何找到最小的行总数并在二维数组中显示相应的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31368606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com