/*********************************************************** 讀入複雜檔案算成績,格式化輸出到另一個檔案 ***********************************************************/ import java.io.*; import java.text.DecimalFormat; //要加入 java.util才行 import java.util.*; public class demo29e{ public static void main(String args[]) throws IOException { //程式進入點 String getbr,getfr,outname; BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); int i,j; double sum; StringTokenizer stk; String name[]=new String [200]; double score[][]=new double [200][7];//最多兩百個學生 double total; DecimalFormat df = new DecimalFormat("###.00");//設定格式 /*****請使用者輸入檔案名稱**********/ System.out.print("請輸入來源檔案名稱:"); getbr = br.readLine(); //取得input file System.out.print("請輸入目標檔案名稱:"); outname = br.readLine(); //取得output file /**** open file *********/ BufferedReader fr= new BufferedReader(new FileReader(getbr)); BufferedWriter fw= new BufferedWriter(new FileWriter(outname)); i=0; sum=0; while (fr.ready())//如果檔案沒有讀完,就繼續處理 { getfr = fr.readLine(); //取得一行輸入 stk=new StringTokenizer(getfr," \n\t"); //取得token try{ name[i]=stk.nextToken(); for (j=0;j<7;j=j+1) { score[i][j]=Double.parseDouble(stk.nextToken()); } total=score[i][0]*2+score[i][1]+score[i][2]+score[i][3]*0.2 +score[i][4]*2+score[i][5]+score[i][6]*0.3; i=i+1; } catch(NumberFormatException e){ //處理輸入文字 System.out.println(getfr+" 這個成績格式有問題!"); continue; } fw.write("第 "+name[i-1]+"號 "+df.format(total)+" 分"); //寫入檔案 fw.newLine(); sum=sum+total; }//while fr.ready() fr.close(); //close file sum=sum/(double) i; fw.write("全班總平均: "+df.format(sum) +" 分"); fw.newLine(); fw.close(); } //main 結束 }