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