8.4 (计算每个雇员每周工作的小时数)假设所有雇员每周工作的小时数存储在一个二维数组中。每行将一个雇 员 7天的工作时间记录在7 列中。例如:右面显示的 数组存储了 8 个雇员的工作时间。编写一个程序,按 照总工时降序的方式显示雇员和他们的总工时。 (用接口及Arrays.sort)
package Homework;
import java.util.Arrays;
interface Comaprable { //用于比较两个员工的接口
public int comparableTo(Object other);
}
public class Exercise8_4_03 {
private static int[][] workHours = { //测试用工时
{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}};
public static void main(String[] args) {
int TotalHour[] = new int[8]; //生成一个装员工总工时的数组TotalHour
int temp;
for (int a = 0; a < 8; a++) {
temp = 0;
for (int b = 0; b < 7; b++) {
temp += workHours[a][b];
}
TotalHour[a] = temp;
}
Employee[] staff = new Employee[8];
for (int i = 0; i < 8; i++) { //将每个员工的名字与工作时长放进staff数组中
staff[i] = new Employee("Employee"+i, TotalHour[i]);
}
Arrays.sort(staff);
for (Employee e : staff) { //打印降序排列的员工及总工时
System.out.println(e.getName() + " TotalWorkHours=" + e.getTotalHour());
}
}
}
class Employee implements Comparable<Employee> {
private String name;
private int TotalHour;
public Employee(String name, int TotalHour) {
this.name = name;
this.TotalHour = TotalHour;
}
public String getName() {
return name;
}
public int getTotalHour() {
return TotalHour;
}
public int compareTo(Employee o1) {
return o1.TotalHour-TotalHour; //降序排列:o1.TotalHour-TotalHour; 升序排列则为TotalHour-o1.TotalHour;
}
}
输出结果如下: