展开全部
java代码如下:import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
/**
*
* @author young
*
*/
class Stu implements Comparable {
private String no;
private String name;
private int yw;
private int math;
private int eng;
private int kx;
private int sum;
public Stu(String no, String name, int yw, int math, int eng, int kx) {
e69da5e887aa3231313335323631343130323136353331333337386663super();
this.no = no;
this.name = name;
this.yw = yw;
this.math = math;
this.eng = eng;
this.kx = kx;
this.sum = this.yw + this.math + this.eng + this.kx;
}
// 三个返回结果都要写出来
public int compareTo(Stu o) {
if (this.sum > o.sum) {
return 1;
} else if (this.sum
return -1;
} else {
return 0;
}
}
@Override
public String toString() {
return "学号:" + this.no + ". 姓名:" + this.name + ". 语文:" + this.yw
+ ". 数学:" + this.math + ". 英语:" + this.eng + ". 科学:" + this.kx
+ ". 总分:" + this.sum;
}
public String display() {
return this.no + "\t" + this.name + "\t" + this.yw + "\t" + this.math
+ "\t" + this.eng + "\t" + this.kx + "\t" + this.sum;
}
}
public class Test {
public static void main(String[] args) {
List list = new ArrayList();
Scanner sc = new Scanner(System.in);
FileWriter fw = null;
System.out.println("输入学生人数: ");
String n = sc.nextLine();
int i = 0, mc = 1;
try {
fw = new FileWriter(new File("c:\\stu.txt"));
fw.write("学号\t姓名\t语文\t数学\t英语\t科学\t总分\t名次");
fw.write("\r\n");
fw.flush();
while (true) {
System.out
.println("输入第[" + (i + 1) + "]个学生的学号,姓名,语文,数学,英语,科学:");
String str = sc.nextLine();
String[] strs = str.split(" ");
Stu s = new Stu(strs[0], strs[1], Integer.valueOf(strs[2]),
Integer.valueOf(strs[3]), Integer.valueOf(strs[4]),
Integer.valueOf(strs[5]));
list.add(s);
i++;
if (i == Integer.valueOf(n)) {
break;
}
}
Collections.sort(list);
System.out.println("按照总分进行排序输出: ");
for (int j = list.size() - 1; j >= 0; j--) {
System.out.println(list.get(j).toString());
fw.write(list.get(j).display());
fw.write("\t" + String.valueOf(mc));
fw.write("\r\n");
fw.flush();
mc++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
执行后会在C盘生成stu.txt文件
eclipse控制台输入输出结果如图:
控制台输入时 每个学生单个信息之间都要有空格隔开。