集合到文件数据排序改进版
生活随笔
收集整理的這篇文章主要介紹了
集合到文件数据排序改进版
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
案例需求
-
鍵盤錄入5個學生信息(姓名,語文成績,數學成績,英語成績)。要求按照成績總分從高到低寫入文本文件
-
格式:姓名,語文成績,數學成績,英語成績 舉例:林青霞,98,99,100
分析步驟
定義學生類
創建TreeSet集合,通過比較器排序進行排序
鍵盤錄入學生數據
創建學生對象,把鍵盤錄入的數據對應賦值給學生對象的成員變量
把學生對象添加到TreeSet集合
創建字符緩沖輸出流對象
遍歷集合,得到每一個學生對象
把學生對象的數據拼接成指定格式的字符串
調用字符緩沖輸出流對象的方法寫數據
釋放資源
代碼實現
-
學生類
測試類
public class TreeSetToFileDemo {public static void main(String[] args) throws IOException {//創建TreeSet集合,通過比較器排序進行排序TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {@Overridepublic int compare(Student s1, Student s2) {//成績總分從高到低int num = s2.getSum() - s1.getSum();//次要條件int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num;int num3 = num2 == 0 ? s1.getMath() - s2.getMath() : num2;int num4 = num3 == 0 ? s1.getName().compareTo(s2.getName()) : num3;return num4;}});//鍵盤錄入學生數據for (int i = 0; i < 5; i++) {Scanner sc = new Scanner(System.in);System.out.println("請錄入第" + (i + 1) + "個學生信息:");System.out.println("姓名:");String name = sc.nextLine();System.out.println("語文成績:");int chinese = sc.nextInt();System.out.println("數學成績:");int math = sc.nextInt();System.out.println("英語成績:");int english = sc.nextInt();//創建學生對象,把鍵盤錄入的數據對應賦值給學生對象的成員變量Student s = new Student();s.setName(name);s.setChinese(chinese);s.setMath(math);s.setEnglish(english);//把學生對象添加到TreeSet集合ts.add(s);}//創建字符緩沖輸出流對象BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\ts.txt"));//遍歷集合,得到每一個學生對象for (Student s : ts) {//把學生對象的數據拼接成指定格式的字符串//格式:姓名,語文成績,數學成績,英語成績StringBuilder sb = new StringBuilder();sb.append(s.getName()).append(",").append(s.getChinese()).append(",").append(s.getMath()).append(",").append(s.getEnglish()).append(",").append(s.getSum());// 調用字符緩沖輸出流對象的方法寫數據bw.write(sb.toString());bw.newLine();bw.flush();}//釋放資源bw.close();} }?
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的集合到文件数据排序改进版的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 文件到集合改进版【应用】
- 下一篇: 复制单级文件夹【应用】