8.4用Array.sort对雇员每周工作的小时数进行排序(接口)

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;
        }
    }


输出结果如下:
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Z-xina

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值