本帖最后由 syz1993 于 2015-1-9 09:33 编辑
- <p>package com.heima;
- /**
- *
- * 有五个学生,每个学生有3门课(语文、数学、英语)的成绩,写一个程序接收从键盘输入学生的信息,
- * 输入格式为:name,30,30,30(姓名,三门课成绩),然后把输入的学生信息按总分从高到低的
- * 顺序写入到一个名称"stu.txt"文件中。要求:stu.txt文件的格式要比较直观,打开这个文件,
- * 就可以很清楚的看到学生的信息。
- * @author syz
- *
- */
- import java.io.*;
- import java.util.*;
- public class Test4 {
- public static void main(String[] args) {
- BufferedReader bufr=null;
- BufferedWriter bufw=null;
- TreeMap<Integer,String> tm=new TreeMap<Integer,String>();
- String line=null;
- System.out.println("请按格式进行输入(格式:name,30,30,30(姓名,三门课成绩)");
- try {
- bufr=new BufferedReader(new InputStreamReader(System.in));
- bufw=new BufferedWriter(new FileWriter("stu.txt"));
- while((line=bufr.readLine())!=null)
- {
- if(line.equals("over"))
- {
- break;
- }
- if(isOk(line))
- {
- //将总分最为key,和输入的数据作为value存入TreeMap集合,默认会按成绩从小到大排序
- String[]strs=line.split(",");
- tm.put(sum(strs), line);
- }else
- {
- System.out.println("输入格式不正确,请重新输入");
- continue;
- }
-
- }
- //把TreeMap的value存入Collection集合
- Collection<String> coll=tm.values();
- //把Collection集合存入List集合,并进行反转
- List<String>list=new ArrayList<String>(coll);
- Collections.reverse(list);
- Iterator<String> it=list.iterator();
- String geshi=" 成绩表 ";
-
- bufw.write(geshi);
- bufw.newLine();
- //把数据存入文件中
- while(it.hasNext())
- { String str=it.next();
- System.out.println(str);
- String[]s=str.split(",");
- bufw.write("姓名:"+s[0]);
- bufw.write("\t");
- bufw.write(" ");
- bufw.write("语文成绩:"+s[1]);
- bufw.write("\t");
- bufw.write(" ");
- bufw.write("数学成绩:"+s[2]);
- bufw.write("\t");
- bufw.write(" ");
- bufw.write("英语成绩:"+s[3]);
- bufw.write("\t");
-
- //System.out.println(it.next());
- bufw.newLine();
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- finally
- {
- if(bufr!=null)
- try {
- bufr.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- if(bufw!=null)
- try {
- bufw.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- }
- //判断输入格式是否正确
- public static boolean isOk(String str)
- {
- String s=".+,[1-9]\\d*0*,[1-9]\\d*0*,[1-9]\\d*0*";
-
- return str.matches(s);
- }
- //求出总分是多少
- public static int sum(String[] str)
- { int s=0;
- for (int i = 1; i < str.length; i++) {
- s+=Integer.parseInt(str[i]);
- }
- return s;
- }
- }
- //创建一个学生类
- class Student
- {
- private String name;
- private int chinese;
- private int math;
- private int english;
- public Student(String name, int chinese, int math, int english) {
- super();
- this.name = name;
- this.chinese = chinese;
- this.math = math;
- this.english = english;
- }
- }</p>
复制代码 做的时间有点长了,唉~要是面试就完了,不过还是做出来了。(下面发了修改了的)
|
|