1.键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低存入文本文件
public class test1 {
public static void main(String[]args) throws Exception {
//创建一个集合,并实现排序功能
TreeSet<student> ts = new TreeSet<student>(new Comparator<student>() {
@Override
public int compare(student s1, student s2) {
int sum1=s1.getCinese()+s1.getMath()+s1.getEnglish();
int sum2=s2.getCinese()+s2.getMath()+s2.getEnglish();
int num=sum2-sum1;
int num2=num==0?s1.getCinese()-s2.getCinese():num;
int num3=num2==0?s1.getMath()-s2.getMath():num2;
int num4=num3==0?s1.getEnglish()-s2.getEnglish():num3;
return num4;
}
});
//创建学生对象并键盘录入信息
for(int i=1;i<=2;i++) {
System.out.println("请输入第"+i+"个学生的姓名,语文,数学,英语成绩");
Scanner sc=new Scanner(System.in);
String name=sc.nextLine();
int chinese=sc.nextInt();
int math=sc.nextInt();
int english=sc.nextInt();
//创建学生类对象
student s=new student();
s.setName(name);
s.setCinese(chinese);
s.setMath(math);
s.setEnglish(english);
//将学生类对象存入集合
ts.add(s);
}
BufferedWriter bw = new BufferedWriter(new FileWriter("students.txt"));
bw.newLine();
bw.flush();
bw.write("姓名,语文成绩,数学成绩,英语成绩");
bw.newLine();
bw.flush();
//遍历集合,将集合中的数据写入文本文件
for (student s : ts) {
StringBuffer sb = new StringBuffer();
sb.append(s.getName()).append(",").append(s.getCinese())
.append(",").append(s.getMath()).append(",")
.append(s.getEnglish());
bw.write(sb.toString());
bw.newLine();
bw.flush();
}
}
}
public class student{
private String name;
private int cinese;
private int math;
private int english;
public student() {
super();
// TODO Auto-generated constructor stub
}
public student(String name, int cinese, int math, int english) {
super();
this.name = name;
this.cinese = cinese;
this.math = math;
this.english = english;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCinese() {
return cinese;
}
public void setCinese(int cinese) {
this.cinese = cinese;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
@Override
public String toString() {
return "student [name=" + name + ", cinese=" + cinese + ", math=" + math + ", english=" + english + "]";
}
}
2.已知s.txt文件中有这样的一个字符串:“hcexfgijkamdnoqrzstuvwybpl”
请编写程序读取数据内容,把数据排序后写入ss.txt中。
public class test2 {
public static void main(String[]args) throws Exception {
//创建字符缓冲输入流对象
BufferedReader br=new BufferedReader(new FileReader("s.txt"));
//读取文本文件中的内容,将其转换成字符串
String s=br.readLine();
//将字符串转换成字符数组
char[]chs=s.toCharArray();
//对字符数组进行排序
Arrays.sort(chs);
//将字符数组转换成字符串
String ss=new String(chs);
//将排好序的字符串存入文本文件中
//创建字符缓冲输出流
BufferedWriter bw=new BufferedWriter(new FileWriter("ss.txt"));
bw.write(ss);
bw.flush();
//关闭流
br.close();
bw.close();
}
}