我特意写的规范了一些
楼主看一下希望有帮助吧
12楼写的太混乱了 3楼和我这个异曲同工吧
我建了Sutdent的类和对象 用接口进行了排序 这样方便一点感觉 最好不要用一对字符串当处理的对象 很混乱 组织成对象好些
如果不是遍历 是取出某有个特定下标的值 数组最好不要用数字 用有特殊意义的常量
这样可读性更强些
文件每行是一个记录的 用BufferReader和Writer最恰当 因为有readLine和writeLine方法
用集合类进行管理感觉对这种问题比较合适
这样复用性强一些感觉
还有可以改进的地方 感觉用串行化更好 但要是非输出文本 就这样吧
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Manager {
private BufferedReader input;
private BufferedWriter output;
private ArrayList<Student> students;//存放所有的学生对象的List
//读入文件
public void read() {
students = new ArrayList<Student>();
try {
this.input = new BufferedReader(new FileReader("C:\\Users\\Administrator\\Desktop\\2.txt"));
String s = new String();
while ((s = input.readLine()) != null) {
String[] nameAndScore = s.split(" ");
this.students.add(new Student(nameAndScore[Student.NAME],
Integer.parseInt(nameAndScore[Student.SCORE])));
}
this.sort();//按分数将学生排序
this.input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
//写回文件
public void write() {
try {
this.output = new BufferedWriter(new FileWriter("C:\\Users\\Administrator\\Desktop\\3.txt"));
for (Student s : this.students) {
output.write(s.toString(), 0, s.toString().length());
output.newLine();
}
this.output.write(String.valueOf(this.average()), 0, String.valueOf(this.average()).length());//写入平均值
this.output.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
//排序
private void sort() {
Collections.sort(this.students, new Comparator<Student>() {
public int compare(Student o1, Student o2) {
return o2.getScore() - o1.getScore();
}
});
}
//求平均值
public float average() {
float average = (float) 0;
for (Student s : this.students) {
average += s.getScore();
}
return average / (this.students.size());
}
public static void main(String[] args) {
Manager m = new Manager();
m.read();
m.write();
}
}
//Student类
class Student {
private String name;
private int score;
public static int NAME = 0;
public static int SCORE = 1;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public int getScore() {
return score;
}
@Override
public String toString() {
return name + " " + score;
}
}
温馨提示:答案为网友推荐,仅供参考