Java50道经典习题-程序50 文件IO
题目:有五个学生,每个学生有3门课的成绩,从键盘输入以上数据(包括学生号,姓名,三门课成绩),计算出平均成绩,将原有的数据和计算出的平均分数存放在磁盘文件"stud"中。
1 import java.io.*; 2 public class Prog50{ 3 //定义学生模型 4 String[] number = new String[5]; 5 String[] name = new String[5]; 6 float[][] grade = new float[5][3]; 7 float[] sum = new float[5]; 8 public static void main(String[] args) throws Exception{ 9 Prog50 stud = new Prog50(); 10 stud.input(); 11 stud.output(); 12 } 13 //输入学号、姓名、成绩 14 void input() throws IOException{ 15 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 16 //录入状态标识 17 boolean isRecord = true; 18 while(isRecord){ 19 try{ 20 for(int i=0;i<5;i++){ 21 System.out.print("请输入学号:"); 22 number[i] = br.readLine(); 23 System.out.print("请输入姓名:"); 24 name[i] = br.readLine(); 25 for(int j=0;j<3;j++){ 26 System.out.print("请输入第"+(j+1)+"门课成绩:"); 27 grade[i][j] = Integer.parseInt(br.readLine()); 28 } 29 System.out.println(); 30 sum[i] = grade[i][0]+grade[i][1]+grade[i][2]; 31 } 32 isRecord = false; 33 }catch(NumberFormatException e){ 34 System.out.println("请输入一个数字!"); 35 } 36 } 37 } 38 //输出文件 39 void output() throws IOException{ 40 FileWriter fw = new FileWriter("D:\\JavaEE\\Code\\Java基础50道经典练习题\\src//stud.txt"); 41 BufferedWriter bw = new BufferedWriter(fw); 42 bw.write("No. "+"Name "+"grade1 "+"grade2 "+"grade3 "+"average"); 43 bw.newLine(); 44 for(int i=0;i<5;i++){ 45 bw.write(number[i]); 46 bw.write(" "+name[i]); 47 for(int j=0;j<3;j++) 48 bw.write(" "+grade[i][j]); 49 bw.write(" "+(sum[i]/5)); 50 bw.newLine(); 51 } 52 bw.close(); 53 } 54 } 55 /*运行结果 56 在D:\JavaEE\Code\Java基础50道经典练习题\src路径下的stud.txt文件中录入了如下数据 57 No. Name grade1 grade2 grade3 average 58 1 张三 10.0 20.0 30.0 12.0 59 2 李四 20.0 30.0 40.0 18.0 60 3 王五 30.0 40.0 50.0 24.0 61 4 赵六 40.0 50.0 60.0 30.0 62 5 周七 50.0 60.0 70.0 36.0 63 */
The only way to do great work is to love what you do.