这是我的代码:- package com.success;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.InputStreamReader;
- import java.io.PrintStream;
- import java.util.Comparator;
- import java.util.Date;
- import java.util.TreeSet;
- /*有五个学生,每个学生有3门课(语文、数学、英语)的成绩,写一个程序接收从键盘输入学生的信息,
- 输入格式为:name,30,30,30(姓名,三门课成绩),
- 然后把输入的学生信息按总分从高到低的顺序写入到一个名称"stu.txt"文件中。
- 要求:stu.txt文件的格式要比较直观,打开这个文件,就可以很清楚的看到学生的信息。*/
- public class Success12 {
- public static void main(String[] args) throws Exception {
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- TreeSet<Student> tm = new TreeSet<Student>(new Comp());
- File f = new File("d:\\" + new Date().getTime() + ".txt");
- String line = null;
- String[] arr = null;
- while ((line = br.readLine()) != null) {
- if ("".equals(line))
- break;
- arr = line.split(",");
- tm.add(new Student(arr[0], arr[1], arr[2], arr[3]));
- }
- br.close();
- // 获取名字和成绩的最大长度
- int nameMaxLen = 0, scoreMaxLen = 0;
- for (Student s : tm) {
- if (s.getName().length() > nameMaxLen)
- nameMaxLen = s.getName().length();
- if (s.getYw().length() > scoreMaxLen)
- scoreMaxLen = s.getYw().length();
- if (s.getSx().length() > scoreMaxLen)
- scoreMaxLen = s.getSx().length();
- if (s.getYy().length() > scoreMaxLen)
- scoreMaxLen = s.getYy().length();
- }
- System.out.println("nameMaxLen:" + nameMaxLen);
- System.out.println("scoreMaxLen:" + scoreMaxLen);
- System.setOut(new PrintStream(f));// 设置默认输出设备为文件f
- //按格式打印到文件f中
- System.out.printf("%" + (nameMaxLen * 2 - 2) + "s%" + (scoreMaxLen + 1)
- + "s%" + (scoreMaxLen + 1) + "s%" + (scoreMaxLen + 1) + "s",
- "名字", "语文", "数学", "英语");
- System.out.println();
- for (Student s : tm) {
- System.out
- .printf("%" + (nameMaxLen) + "s%" + (scoreMaxLen + 3)
- + "s%" + (scoreMaxLen + 3) + "s%"
- + (scoreMaxLen + 3) + "s", s.getName(), s.getYw(),
- s.getSx(), s.getYy());
- System.out.println();
- }
- }
- }
- class Student {
- String name;
- String yw;
- String sx;
- String yy;
- Student(String name, String yw, String sx, String yy) {
- this.name = name;
- this.yw = yw;
- this.sx = sx;
- this.yy = yy;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getYw() {
- return yw;
- }
- public void setYw(String yw) {
- this.yw = yw;
- }
- public String getSx() {
- return sx;
- }
- public void setSx(String sx) {
- this.sx = sx;
- }
- public String getYy() {
- return yy;
- }
- public void setYy(String yy) {
- this.yy = yy;
- }
- }
- class Comp implements Comparator<Student> {
- @Override
- public int compare(Student s1, Student s2) {
- int sum1 = (int) (Double.parseDouble(s1.getYw())
- + Double.parseDouble(s1.getSx()) + Double.parseDouble(s1
- .getYy()));
- int sum2 = (int) (Double.parseDouble(s2.getYw())
- + Double.parseDouble(s2.getSx()) + Double.parseDouble(s2
- .getYy()));
- return new Integer(sum2).compareTo(new Integer(sum1));
- }
- }
复制代码 可以看到我是默认 学生姓名 都是汉字
所以如果 学生姓名 含英文就会引起格式错乱
不知道该怎么修改??
|
|