JAVA写个东西读取TXT中的数据 且要计算出平均值和总值 最后还要按总值排序。
2014-07-05 · 知道合伙人数码行家
关注
展开全部
import java.io.*;
import java.util.*;
public class FileNumberDemo {
public static void main(String[] args) throws IOException{
File file = new File("D:\\a.txt");
if(!file.exists())
throw new RuntimeException("文件不存在!");
BufferedReader br = new BufferedReader(new FileReader(file));
BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\b.txt"));
String str = null;
List<String> list = new ArrayList<String>();
while((str=br.readLine())!=null){
list.add(str);
}
String[] arr = new String[list.size()];
TreeSet<Student> tr = new TreeSet<Student>();
arr = list.toArray(arr);
for(int i = 0; i < arr.length; i++){
String[] line = arr[i].split(" +");
for(int j = 0; j < line.length; j++){
if(i == 0)
bw.write(line[j]+"\t");
else{
tr.add(new Student(Integer.parseInt(line[0]),
line[1],Integer.parseInt(line[2]),
Integer.parseInt(line[3]),Integer.parseInt(line[4]),
(Integer.parseInt(line[2])+Integer.parseInt(line[3])+Integer.parseInt(line[4])/3),
(Integer.parseInt(line[2])+Integer.parseInt(line[3])+Integer.parseInt(line[4]))));
}
}
System.out.println();
}
bw.write("\r\n");
int num = 1;
for(Iterator<Student> it = tr.iterator(); it.hasNext();){
bw.write(it.next().toString());
bw.write("\t"+(num++)+"\r\n");
}
bw.close();
}
}
class Student implements Comparable<Student>{
private int num;
private String name;
private int yw;
private int sx;
private int english;
private int pj;
private int sum;
public Student(int num,String name,int yw,int sx,int english,int pj, int sum){
this.num = num;
this.name = name;
this.yw = yw;
this.sx = sx;
this.english = english;
this.pj = pj;
this.sum = sum;
}
public int compareTo(Student stu) {
int num = Integer.valueOf(stu.sum).compareTo(Integer.valueOf(this.sum));
if(num == 0)
return Integer.valueOf(stu.num).compareTo(Integer.valueOf(this.num));
return num;
}
public String toString(){
return num+"\t"+name+"\t"+yw+"\t"+sx+"\t"+english+"\t"+pj+"\t"+sum;
}
}
//输出到b.txt的结果:
学号 姓名 语文 数学 英语 平均值 总值 排序
28 陈祥枭 82 96 91 208 269 1
11 林宏旦 91 90 76 206 257 2
............
............
............
17 翁文秀 57 43 58 119 158 36
来自:求助得到的回答
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询