/*
*
*有五个学生,每个学生有3门课(语文、数学、英语)的成绩,
* 写一个程序接收从键盘输入学生的信息,输入格式为:name,30,30,30(姓名,三门课成绩),
* 然后把输入的学生信息按总分从高到低的顺序写入到一个名称"stu.txt"文件中。
* 要求:stu.txt文件的格式要比较直观,打开这个文件,就可以很清楚的看到学生的信息。
* 采用DAO模式,定义两个类 Student学生信息实体(POJO),StudentDao(DAO)类实现数据
* 到文件的控制.
* Strudent->name (String)
* yuwen (int)
* shuxue (int)
* yingyu (int)
* 构造器 Strudenet(String name,int yuwen,int shuxue,int yingyu)
* 为了方便生成String 重写 toString()
* Student-> path (String) 文件路径
* sc (Scanner) 键盘录入
* writer (Writer) 字符流
* bufwrter (BufferedWriter) 缓冲
* list (ArrayList) 存储学生列表
*
* inPut():void 完成键盘录入 拆分字符串,封装学生信息
* setList():List 构造学生列表
* oder(List):void 排序
*
*
* out() 方法 键盘录入
*
*
* */
@SuppressWarnings("all")
public class StudentIO {
private Student[] arr;
private String path;
private Scanner sc;
private Writer writer;
private BufferedWriter bufwrter;
public void inPut() {
int i = 0;
ArrayList<Student> list = new ArrayList<Student>();
sc = new Scanner(System.in);
while (i < 5) {
System.out.println("请输入" + (i + 1) + "个学生");
String s = sc.next();
String[] tmparr = s.split(",");
list.add(new Student(tmparr[0], new Integer(tmparr[1]),
new Integer(tmparr[2]), new Integer(tmparr[3])));
i++;
}
// Student[] tarr=new Student[2];
arr = new Student[list.size()];
arr = list.toArray(arr);
}
public void oderby() {
Student tmpstu = null;
/*Student[] stuarr = new Student[arr.length];
for (int i = 0; i < stuarr.length - 1; i++) {
for (int j = 0; j < stuarr.length - i - 1; j++) {
if (arr[j].getSum() < arr[j + 1].getSum()) {
Student tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}*/
Arrays.sort(arr);
}
private void writerFile() {
try {
this.path = "/home/cys/stu.txt";
writer = new FileWriter(path);
bufwrter = new BufferedWriter(writer);
bufwrter.write("名字\t语文\t数学\t英语\t总分"); //输出一个表头,stu.txt文件的格式要比较直观
bufwrter.newLine();
for (Student student : arr) {
bufwrter.write(student.toString());
bufwrter.newLine();
}
bufwrter.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
bufwrter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void forech() {
for (Student student : arr) {
System.out.println(student);
}
}
public static void main(String[] args) {
StudentIO stuIO = new StudentIO();
// Student stu=new Student("张三", 50, 50, 100);
stuIO.inPut();
stuIO.oderby();
stuIO.writerFile();
stuIO.forech();
}
}
|
|