import java.util.*;
import java.util.Arrays;
public class EmployeeWeeklyHours{
public static void main(String[] args) {
int[][] employeeHours= new int[][] {
{ 2, 4, 3, 4, 5, 8, 8},
{ 7, 3, 4, 3, 3, 4, 4},
{ 3, 3, 4, 3, 3, 2, 2},
{ 9, 3, 4, 7, 3, 4, 1},
{ 3, 5, 4, 3, 6, 3, 8},
{ 3, 4, 4, 6, 3, 4, 4},
{ 3, 7, 4, 8, 3, 8, 4},
{ 6, 3, 5, 9, 2, 7, 9}};
int [] finalHours = new int[8];
for (int i = 0; i < finalHours.length; i++) {
int total = 0;
for (int j = 0; j < finalHours.length - 1; j++) {
total += employeeHours[i][j];
finalHours[i] = total;
}
}
java.util.Arrays.sort(finalHours);
int[] sort = new int[finalHours.length];
for (int i = 0; i < finalHours.length; i++)
sort[i] = finalHours[i];
for (int i = 7; i > -1; i--)
System.out.println(sort[i]);
}
}员工0: 2 4 3 4 5 8 8
员工1: 7 3 4 3 3 4 4
员工2: 3 3 4 3 3 2 2
员工3: 9 3 4 7 3 4 1
员工4: 3 5 4 3 6 3 8
员工5: 3 4 4 6 3 4 4
员工6: 3 7 4 8 3 8 4
员工7: 6 3 5 9 2 7 9
正如您从我的代码中看到的,我应该按降序列出每个员工的总工作时数。然而,我似乎很难找到一种方法来显示员工总工时旁边的数字。
例如。“7号员工工作了42个小时。
有没有什么方法可以将员工编号与排序后的编号一起列出,而无需对其进行硬编码?我觉得我的问题有一个简单的答案,但现在脑海中什么都没有。
发布于 2016-01-27 08:47:48
一种解决方案是使用TreeMap,因为它会自动对键进行排序。
TreeMap<Integer, Integer> treeMap =
new TreeMap<Integer, Integer>(Collections.reverseOrder());
for (int i = 0; i < finalHours.length; i++) {
treeMap.put(finalHours[i], i);
}
for (Entry<Integer, Integer> entry : treeMap.entrySet()) {
System.out.println( "Employee " + entry.getValue() + " worked " + entry.getKey() + " hours.");
}发布于 2016-01-27 08:38:00
for (int i=0; i < finalHours.length; i++) {
System.out.println(String.format("Employee %d worked %d hours.", i, finalHours[i]));
}既然你提到了硬编码,当你写一个循环时,不要在里面放一个神奇的"7“,而是使用像finalHours.length或employeeHours.length这样的变量。同样的原则在一般情况下也适用:即使你“知道”值是什么,也要引用变量。
发布于 2016-01-27 08:38:16
如果你想要这段代码?
import java.util.*;
import java.util.Arrays;
public class EmployeeWeeklyHours{
public static void main(String[] args) {
int[][] employeeHours= new int[][]{
{ 2, 4, 3, 4, 5, 8, 8},
{ 7, 3, 4, 3, 3, 4, 4},
{ 3, 3, 4, 3, 3, 2, 2},
{ 9, 3, 4, 7, 3, 4, 1},
{ 3, 5, 4, 3, 6, 3, 8},
{ 3, 4, 4, 6, 3, 4, 4},
{ 3, 7, 4, 8, 3, 8, 4},
{ 6, 3, 5, 9, 2, 7, 9}};
String [] finalHours = new String[8];
for (int i = 0; i < finalHours.length; i++)
{
int total = 0;
for (int j = 0; j < finalHours.length-1; j++)
{
total += employeeHours[i][j];
finalHours[i] = "Employee "+ i+" worked "+total + "hours";
}
}
java.util.Arrays.sort(finalHours);
String[] sort = new String[finalHours.length];
for (int i = 0; i < finalHours.length; i++)
{
sort[i] = finalHours[i];
}
for (int i = 7; i > -1; i--)
{
System.out.println(sort[i]);
}
}
}结果是
Employee 7 worked 41hours
Employee 6 worked 37hours
Employee 5 worked 28hours
Employee 4 worked 32hours
Employee 3 worked 31hours
Employee 2 worked 20hours
Employee 1 worked 28hours
Employee 0 worked 34hours使用int[]替代String[],这样您就可以获得该结果。再见。
https://stackoverflow.com/questions/35026394
复制相似问题