Java 编程练习实现compareable接口

1

完成动物的年龄排序。(40分)

题目内容:

通常来说动物的物理年龄与其生理年龄是不匹配的,如果要严格的根据动物的生理年龄排序需要有一个具体的参照(例如人)。下面列出了狗和人以及猫和人的年龄对照表。

 

1

2

3

4

5

6

7

8

9

10

18

23

28

32

36

40

45

50

55

60

 

1

2

3

4

5

6

7

8

9

10

15

24

28

32

36

40

44

48

52

56

例如,1岁的狗与1岁的猫相比,1岁的狗生理年龄较大。请利用继承机制与Comparable接口实现不同狗与猎豹对象的排序。下面给出了程序的基本框架,请给出相关的函数实现。

 

按照题目代码给出的实现,其中要注意comparable接口为泛型。

import java.util.Arrays;
import java.util.Scanner;

class Animal {

    int age;//动物年龄

    int mage; //映射到人的年龄

    String name; //名字

    static int[] dog = {0,18,23,28,32,36,40,45,50,55,60};

    static int[] cat= {0,15,24,28,32,36,40,44,48,52,56};

    Animal(String name, int age){
        this.name = name;
        this.age = age;
    }

}

class Dog extends Animal implements Comparable<Animal>{

    Dog(String name, int age){
        super(name,age);
        this.mage = dog[age];
    }

    @Override
    public int compareTo(Animal o) {
        return this.mage - o.mage;
    }
}

class Cat extends Animal implements Comparable<Animal>{
    Cat(String name, int age){
        super(name,age);
        this.mage = cat[age];
    }

    @Override
    public int compareTo(Animal o) {
        return this.mage - o.mage;
    }
    //实现你的构造函数与Comparable中的接口

}


public class CompareAnimal {


    public static void main(String[] args) {

        Animal[] as = new Animal[4];

        // 初始化
        Scanner sc = new Scanner(System.in);

        // 利用hasNextXXX()判断是否还有下一输入项

        if (sc.hasNext()) {

            as[0] = new Dog("dog1", sc.nextInt());

        }

        if (sc.hasNext()) {

            as[1] = new Cat("cat1", sc.nextInt());

        }

        if (sc.hasNext()) {

            as[2] = new Dog("dog2", sc.nextInt());

        }

        if (sc.hasNext()) {

            as[3] = new Cat("cat2", sc.nextInt());

        }
        // 请补充排序
        Arrays.sort(as);
        // 请补充升序输出结果
        for(int i=0;i<4;i++){
            System.out.println(as[i].name+","+as[i].age);
        }

    }

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值