JAVA简单成绩计算平均分(含文件读取)

  有五个学生,每个学生有3门课的成绩,从键盘输入以上数据(包括学生号,姓名,三门课成绩),计算出平均成绩,把原有的数据和计算出的平均分数存放在 磁盘文件 "stud"中。


代码:

import java.io.*;
import java.text.DecimalFormat;  

class stu{
	String[] num = new String[5];
    String[] name = new String[5];
    double[][] score = new double[5][3];
    String[] sum = new String[5];
    DecimalFormat    df   = new DecimalFormat("######0.0"); 
    public void input() throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        boolean change =true;
        
        while(change){
           try{
                for(int i = 0;i <= 4;i++){
                    System.out.print("请输入学号 : ");
                    num[i] = br.readLine();
                    System.out.print("请输入姓名 : ");
                    name[i] = br.readLine();
                    for(int j = 0;j <= 2;j++){
                        System.out.print("请输入第 "+(j+1)+"门成绩 : ");
                        score[i][j] = Integer.parseInt(br.readLine());
                        if(score[i][j]>100||score[i][j]<0){
                        	System.out.println("分数超出范围。");
                             input();
                        }
                    }
                    System.out.println();
                    double s = (score[i][0]+score[i][1]+score[i][2])/3.0;
                    sum[i] = df.format(s);
                }
                change =false;
           }
            catch(NumberFormatException nfe){
                System.out.println("分数只能输入数字,不允许输入其他格式,请重新输入。");
            }
        }
    }
    
    public void compositor() throws IOException{
        FileWriter fw = new FileWriter("stud.txt");     //文件存放于"stud.txt"文件;
        BufferedWriter bw = new BufferedWriter(fw);
        for(int i = 0;i <= 4;i++){
        	bw.write(num[4-i]);
            bw.write("  "+name[i]);
            for(int j=0;j < 3;j++) bw.write(" "+score[i][j]);
            bw.write(" "+sum[i]);
            bw.newLine();
        }
        bw.close();
    }
     
    public static void main(String[] args) throws IOException{
        stu s = new stu();
        s.input();
        s.compositor();
    }
}

你可能感兴趣的:(JAVA简单成绩计算平均分(含文件读取))