黑马程序员技术交流社区
标题: 4、 有五个学生,每个学生有3门课(语文、数学、英语)... [打印本页]
作者: 唐洪超 时间: 2015-12-16 15:31
标题: 4、 有五个学生,每个学生有3门课(语文、数学、英语)...
/**
* 4、 有五个学生,每个学生有3门课(语文、数学、英语)的成绩,
* 写一个程序接收从键盘输入学生的信息, 输入格式为:name,30,30,30
* (姓名,三门课成绩), 然后把输入的学生信息按总分从高到低的顺序写入
* 到一个名称"stu.txt"文件中。要求:stu.txt文件的格式要比较直观,
* 打开这个文件,就可以很清楚的看到学生的信息。
public class Demo04 {
public static void main(String[] args) throws IOException {
Comparator<Student> com = Collections.reverseOrder(); //自定义一个比较器
File fi = new File("c:\\stu.txt"); //指定文件目录.定义在外面更好一些,提高扩展.
Set<Student> se = StudnetIn(com,false); //将比较器传入方法以及排序方式..返回一个集合.
ToFile(se,fi); //将集合和file传入.
}
//对于集合进行遍历,获取对象元素.并输出到指定文件.
public static void ToFile(Set<Student> se,File fi) throws IOException {
Iterator<Student> it = se.iterator();
FileWriter fw = new FileWriter(fi);
while(it.hasNext())
{
Student s = it.next();
fw.write(s.toString() + s.getMax() + "\t"+"\r\n");
}
fw.close();
}
//传入比较器以及排序需求.如果是true,就是默认排序,否则就是自定义的排序.
public static Set<Student> StudnetIn(Comparator<Student> com,boolean bo) {
Scanner s = new Scanner(System.in);
Set<Student> se = null;
if(bo == true) //自然排序.
{
se = new TreeSet<Student>();
}
else //自定义排序(也就是定义的倒序)
{
se = new TreeSet<Student>(com);
}
while(true)
{
String ss = s.nextLine();
if(ss.equals("over")) //输入结束指令.
{
System.out.println("输入结束");
break;
}else
{
//切割,并将字符串和角标传递给student对象,并存入集合中.
String[] str = ss.split(",");
se.add(new Student(str[0],Double.parseDouble(str[1]),
Double.parseDouble(str[2]),Double.parseDouble(str[3])));
}
}
return se;
}
}//定义一个实现Comparable的学生对象.
class Student implements Comparable<Student>
{
private String name;
private Double ch;
private Double ma;
private Double en;
private Double max;
Student(String name,Double ch,Double ma,Double en) //参数直接收语文,数学,英语,为什么?
{
this.name = name;
this.ch = ch;
this.ma = ma ;
this.en = en;
this.max = ch + ma + en; //总成绩是算出来的,不是传入的.
}
public int compareTo(Student stu) //重写compareTo方法.
{//在这里要注意:谁是关键的?我们要比较什么?----成绩是关键的.
int i = new Double(this.max).compareTo(new Double(stu.max));
if(i == 0) //只有成绩相等,再去比较名字.
return this.name.compareTo(stu.name);
return i;
}
public int hashCode() //重写hashCode方法.
{
return (int) (this.name.hashCode() + this.max * 66);
}
public boolean equals(Student stu) //重写equals方法.
{
return this.name.equals(stu.name) && this.max == stu.max;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getCh() {
return ch;
}
public void setCh(Double ch) {
this.ch = ch;
}
public Double getMa() {
return ma;
}
public void setMa(Double ma) {
this.ma = ma;
}
public Double getEn() {
return en;
}
public void setEn(Double en) {
this.en = en;
}
public Double getMax() { //只想对外提供总成绩的get,而不提供set,为什么?
return max;
}
@Override
public String toString() {
return "Student [name=" + name + ", ch=" + ch + ", ma=" + ma + ", en="
+ en + "]";
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |