package com.itheima2.com;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.TreeSet;
public class Test1
{
/**
* 有五个学生,每个学生有3门课(语文、数学、英语)的成绩,写一个程序接收从键盘输入学生的信息,
* 输入格式为:name,30,30,30(姓名,三门课成绩), 然后把输入的学生信息按总分从高到低的顺序写入到一个名称"stu.txt"文件中。
* 要求:stu.txt文件的格式要比较直观,打开这个文件,就可以很清楚的看到学生的信息。
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
// 1.定义一个学生类。
// 2.读入学生信息
// 3.给学生按照总分排序。
// 4.保存为txt文件。
// 获取到集合元素
TreeSet<Student> set = getStudent();
Iterator<Student> it = set.iterator();
while (it.hasNext())
{
Student stu = it.next();
SaveTXT(stu.getstr());
}
// 遍历集合然后打印
}
/**
* 输入学生文本
*
* @return
* @return
*/
public static TreeSet<Student> getStudent() throws Exception
{
System.out.println("输入学生信息");
// 设置装学生的集合
TreeSet<Student> setStu = new TreeSet<Student>();
BufferedReader bfReader = new BufferedReader(new InputStreamReader(
System.in));
String str = "";
Student stu;
String [] stuarry;
while(!(str= bfReader.readLine()).equals("q"))
{
// 获取到字符串要进行过滤
stu = new Student();
stuarry = str.split(",");
stu.name = stuarry[0];
stu.china = Integer.parseInt(stuarry[1]);
stu.math = Integer.parseInt(stuarry[2]);
stu.english = Integer.parseInt(stuarry[3]);
System.out.println(stuarry[0]);
stu.getScores();// 计算总分
setStu.add(stu);// 添加到集合里面去
}
return setStu;
}
/**
* 保存到文件当中
*
* @throws IOException
*/
public static boolean SaveTXT(String txt) throws IOException
{
// 我不知道有多少但是我就不断的写入
BufferedWriter bufWri = new BufferedWriter(new FileWriter(
"student.txt", true));
// 写入到文本
bufWri.write(txt);
bufWri.newLine();
bufWri.flush();
return true;
}
}
/**
* 学生类 ,并且让这个集合具有比较性
*
* @author tianshenjiaoao
*
*/
class Student implements Comparable<Student>
{
String name; // 姓名
int china; // 语文
int math; // 数学
int english; // 英语
int scores; // 总分
Student()
{
}
// 元素具有比较性。 这里可以重新设置测试TreSet的自然比较条件
public int compareTo(Student o)
{
if (this.scores > o.scores)
{
return 1;
} else if (this.scores< o.scores)
{
return -1;
} else
{
return 0;
}
}
/*
* 计算总分
*/
public void getScores()
{
this.scores = this.math + this.china + this.english;
}
/**
* 把所有内容都转化成为字符串
*
* @return
*/
public String getstr()
{
return this.name + " | " + this.china + " | " + this.math + " | "
+ this.english + "总分:" + this.scores;
}
}
有五个学生,每个学生有3门课(语文、数学、英语)的成绩,写一个程序接收从键盘输入学生的信息,
输入格式为:name,30,30,30(姓名,三门课成绩), 然后把输入的学生信息按总分从高到低的顺序写入到一个名称"stu.txt"文件中。要求:stu.txt文件的格式要比较直观,打开这个文件,就可以很清楚的看到学生的信息。