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();
    }
}

  • 1
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值