java使用IO流對數組排序實例講解
在學會了java中io流的使用后,我們對于數組的排序,又多了一種使用方法。大家知道流處理數據的效率是比較理想的,那么在具體操作數組排序上,很多人對于排序的方法還沒有明確。下面我們先java使用流對數組排序的思路為大家進行梳理,然后帶來對應的實例代碼方法。
1、排序思路(1)從字符輸入流中讀取文本,緩沖各個字符,從而實現字符、數組和行的高效讀取
(2)詢問用戶需要多少位數的數組
(3)轉換為數字類型
(4)將用戶輸入數字存入數組
(5)把數組按排序需求并打印出來
2、實例public static void main(String[] args) { // TODO Auto-generated method stub try { //數組a()的數字個數,由用戶輸入決定 InputStreamReader isr=new InputStreamReader(System.in); //從字符輸入流中讀取文本,緩沖各個字符,從而實現字符、數組和行的高效讀取 BufferedReader bfr=new BufferedReader(isr); //詢問用戶需要多少位數的數組 System.out.println('請輸入需要多少位數的數組:n'); String a1=bfr.readLine(); //將a1轉換為數字類型 int i=Integer.parseInt(a1); //提示用戶輸入數組數據 System.out.println('請向數組中存入'+i+'個數據:n'); //將用戶輸入數字存入數組 Integer[] a=new Integer[i]; for(int j=0;j<i;j++){ System.out.println('第'+(j+1)+'個:'); a[j]=new Integer(bfr.readLine()); } //把數組按升序排序并打印出來 for(int k=1;k<i;k++){ for(int m=0;m<(i-k);m++){ if(a[m]>a[m+1]){ //Integer temp=new Integer(0); int temp=0; temp=a[m]; a[m]=a[m+1]; a[m+1]=temp; } } } //輸出排序后的數組 System.out.println('排序后n'); for(int t=0;t<=i;t++){ System.out.println(a[t]); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
實例擴展:
鍵盤錄入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(); }}
到此這篇關于java使用IO流對數組排序實例講解的文章就介紹到這了,更多相關java如何使用流對數組排序內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
