1 、键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低存入文本文件。
代码:
public class TreeSetDemo { public static void main(String[] args) throws IOException{ //创建TreeSet对象,用接口匿名内部类的方式实现Comparator接口 TreeSet<Student> ts=new TreeSet<Student>(new Comparator<Student>() { //重写Comparator接口中的compare()方法 @Override public int compare(Student s1,Student s2) { //主要排序条件:总成绩,按从高到低输出 int num1=s2.sum(s2)-s1.sum(s1); //次要排序条件,当总成绩相同时按学生姓名内容比较 int num2=(num1==0)?s2.getName().length()-s1.getName().length():num1; return num2; } }); //键盘录入学生信息 System.out.println("请输入学生信息:"); for(int x=1;x<6;x++) { Scanner sc=new Scanner(System.in); System.out.print("请输入第"+x+"名学生的姓名:"); String name=sc.nextLine(); System.out.print("请输入第"+x+"名学生的语文成绩:"); int chineseScore=sc.nextInt(); System.out.print("请输入第"+x+"名学生的数学成绩:"); int mathScore=sc.nextInt(); System.out.print("请输入第"+x+"名学生的英语成绩:"); int englishScore=sc.nextInt(); //将录入的学生信息封装到学生对象里 Student s=new Student(); s.setName(name); s.setChineseScore(chineseScore); s.setMathScore(mathScore); s.setEnglishScore(englishScore); //把学生对象添加到集合中 ts.add(s); } //创建字符缓冲输出流对象 BufferedWriter bw=new BufferedWriter(new FileWriter("18-1.txt")); //遍历 for(Student s:ts) { //利用StringBuffer中的追加功能,将需要输出的信息集合在一起 StringBuffer sb=new StringBuffer(); sb.append(s.getName()).append(",").append(s.getChineseScore()).append(",").append(s.getMathScore()) .append(",").append(s.getEnglishScore()).append(",").append(s.sum(s)); //将信息写入文本文件中 bw.write(sb.toString()); //换行 bw.newLine(); //刷新流 bw.flush(); } //关闭流,释放资源 bw.close(); }}
2、已知s.txt文件中有这样的一个字符串:“hcexfgijkamdnoqrzstuvwybpl”
请编写程序读取数据内容,把数据排序后写入ss.txt中。
public class Paixv { public static void main(String[] args) throws IOException { // 读取该文件的内容,存储到一个字符串中 BufferedReader br = new BufferedReader(new FileReader("E:\\西部开源\\作业\\课后练习\\java\\18-2.txt")); String line = br.readLine(); br.close(); // 把字符串转为字符数组 char[] chs = line.toCharArray(); // 对字符数组进行排序 Arrays.sort(chs); // 把排序后的字符数组转换为字符串 String s = new String(chs); // 把字符串再次写入ss.txt中 BufferedWriter bw = new BufferedWriter(new FileWriter("E:\\西部开源\\作业\\课后练习\\java\\18-2W.txt")); bw.write(s); bw.newLine(); // 释放资源 bw.close(); }}
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦