-------android培训、java培训、期待与您交流! ----------
package com.itcast.b21.io.test;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Comparator;
import java.util.TreeSet;
public class StudentCourseOrder
{
/**
* 有五个学生,每个学生有3门课的成绩,
从键盘输入以上数据(包括姓名,三门课成绩),
输入的格式:如:zhagnsan,30,40,60计算出总成绩,
并把学生的信息和计算出的总分数高低顺序存放在磁盘文件"stud.txt"中。
* @throws IOException
*/
public static void main(String[] args) throws IOException
{
//1.建立学生对象,并实现Comparable接口
//2.建立学生集合TreeSet,录入学生信息,到集合中
//3.遍历学生集合,将学生的信息输出到文本文件中
System.out.println("VM:"+Charset.defaultCharset());//以vm的默认字符集作为参照去编码,通用性强
System.out.println("file.encoding:"+System.getProperty("file.encoding"));
Comparator<Student> cmp = Collections.reverseOrder();
TreeSet<Student> students = new TreeSet<Student>(cmp);
inputStuInfo(students);
saveStuInfo(students);
}
public static void saveStuInfo(TreeSet<Student> students) throws IOException
{
PrintWriter pw =
new PrintWriter(new FileWriter("test/stu_info.txt"), true);
for(Student s : students)
{
pw.print(s.getName()+",");
pw.print(s.getChinese()+",");
pw.print(s.getMath()+",");
pw.print(s.getChinese()+s.getMath());
pw.println();
}
pw.close();
}
public static void inputStuInfo(TreeSet<Student> students) throws IOException
{
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
String line = "";
String info[] = null;
Student s = null;
while(null != (line=br.readLine()))
{
if("q".equals(line)) return;
info = line.split(",");
s = new Student(info[0], Integer.parseInt(info[1]), Integer.parseInt(info[2]));
students.add(s);
}
br.close();
}
}
class Student implements Comparable<Student>
{
private String name;
private Integer chinese;
private Integer math;
public Student(String name, int chinese, int math)
{
this.name = name;
this.chinese = chinese;
this.math = math;
}
@Override
public int compareTo(Student s)
{
int r = new Integer(chinese+math).compareTo(new Integer(s.chinese+s.math));
if(0 == r)
return name.compareTo(s.name);
return r;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Integer getChinese()
{
return chinese;
}
public void setChinese(Integer chinese)
{
this.chinese = chinese;
}
public Integer getMath()
{
return math;
}
public void setMath(Integer math)
{
this.math = math;
}
}
-------
android培训
、
java培训
、期待与您交流! ----------