標籤:Java集合知識與IO流知識結合執行個體 選取器排序 TreeSet集合 字元緩衝流 數組排序
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(); }}
Java集合/數組排序知識與IO流結合執行個體