標籤:存在 void i++ tle ext c盤 else 建立 ace
題目:有五個學生,每個學生有3門課的成績,從鍵盤輸入以上資料(包括學生號,姓名,三門課成績),計算出平均成績,把原有的資料和計算出的平均分數存放在磁碟檔案 "stud "中。
import java.io.*; import java.util.*;public class lianxi50 { public static void main(String[] args){ Scanner ss = new Scanner(System.in); String [][] a = new String[5][6]; for(int i=1; i<6; i++) { System.out.print("請輸入第"+i+"個學生的學號:"); a[i-1][0] = ss.nextLine(); System.out.print("請輸入第"+i+"個學生的姓名:"); a[i-1][1] = ss.nextLine(); for(int j=1; j<4; j++) { System.out.print("請輸入該學生的第"+j+"個成績:"); a[i-1][j+1] = ss.nextLine(); } System.out.println("\n"); } //以下計算平均分 float avg; int sum; for(int i=0; i<5; i++) { sum=0; for(int j=2; j<5; j++) { sum=sum+ Integer.parseInt(a[i][j]); } avg= (float)sum/3; a[i][5]=String.valueOf(avg); } //以下寫磁碟檔案 String s1; try { File f = new File("C:\\stud"); if(f.exists()){ System.out.println("檔案存在"); }else{ System.out.println("檔案不存在,正在建立檔案"); f.createNewFile();//不存在則建立 } BufferedWriter output = new BufferedWriter(new FileWriter(f)); for(int i=0; i<5; i++) { for(int j=0; j<6; j++) { s1=a[i][j]+"\r\n"; output.write(s1); } } output.close(); System.out.println("資料已寫入c盤檔案stud中!"); } catch (Exception e) { e.printStackTrace(); } }}
【程式50】