java的健壮性怎么解释_健壮性判断问题(instanceof)

嗯,我这是在基础测试时写的,也考虑到了score是小数,给你参考下

----------------

/**

5、定义一个学生类, 需要有

姓名, 年龄, 考试成绩三个成员属性.

属性(成员变量)需要私有并提供get, set方法,

可以通过构造函数进行初始化。

*/

public class StudentDemo

{

public static void main(String[] args)

{

Student stu = new Student("harry", 15, 88.5) ; //构造一个学生对象;

System.out.println(stu.getName() + "  " + stu.getAge() + "  " +stu.getScore());

stu.setName("cobe");//设置 name ,age ,score;

stu.setAge(26);

stu.setScore(89.5);

System.out.println(stu.getName() + "  " + stu.getAge() + "  " +stu.getScore());

}

}

//将编译得到得Stduent.class和SortMyStuDemo类放同一目录一起编译;

class Student

{

public Student(String name, int age, double score)

{

this.name = name ;

this.age = age ;

this.score = score;

}

public String getName()//获取姓名

{

return name;

}

public int getAge()//获取年龄

{

return age;

}

public double getScore()//获取分数

{

return score;

}

public void setName(String name)//设置姓名

{

this.name = name;

}

public void setAge(int age)//设置年龄

{

this.age = age;

}

public void setScore(double score)//设置分数

{

this.score = score;

}

private String name;

private int age;

private double score;

}

----------------------------

import java.util.*;

public class SortMyStuDemo

{

public static void main(String[] args)

{

TreeSet ts = new TreeSet(new MyCompare());//创建树集,使用MyCompare类排序

ts.add(new Student("Harry" , 14, 87  ));

ts.add(new Student("Ameily", 12, 87.5));

ts.add(new Student("Cobber", 13, 85  ));

ts.add(new Student("Obamar", 17, 84.5));

ts.add(new Student("James" , 19, 86.5));

Iterator it = ts.iterator();

while(it.hasNext())

{   Student stu = it.next();

System.out.println("name="+stu.getName()+"... age="+ stu.getAge()+

"...score="+stu.getScore());

}

}

}

class MyCompare implements Comparator

{

public int compare(Student s1, Student s2)

{

double num = s1.getScore() - s2.getScore();

if ( num == 0)    //分数相同则按照姓名排序

return s1.getName().compareTo(s2.getName());

else if (num > 0) //使用分数的升序排序;

return 1;

return -1;

}

}

/*

不使用comparTo方法直接比较分数;而是利用了compareTo方法的返回值就可比较分数大小,从而返回treeset排序的依据;

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值