0
点赞
收藏
分享

微信扫一扫

Java 标准输入/输出流的程序设计;文件读/写的程序设计应用一

夕颜合欢落 2022-05-02 阅读 55

输入 5 个学生的信息(包含学号、姓名、 3 科成绩),统计各学生的总分,然后将学生信息

和统计结果存入二进制数据文件 STUDENT.DAT 中。

参考代码如下:

import java.util.Scanner;
import java.io.*;

class Student{
    Scanner sc = new Scanner(System.in);
    private String sno; private String name;
    private int s1, s2, s3, sum;
    public Student() {
        String str = sc.nextLine();
        String[] s = str.split(" ");
        this.sno = s[0]; this.name = s[1];
        this.s1 = Integer.parseInt(s[2]);
        this.s2 = Integer.parseInt(s[3]);
        this.s3 = Integer.parseInt(s[4]);
        this.sum = s1+s2+s3;
    }
    public String toString() {//覆写toString()方法,返回学生信息
        return "学号:"+this.sno+" "+"姓名:"+this.name+" "+"s1:"+this.s1
                +" "+"s2:"+this.s2+" "+"s3:"+this.s3+" "+"总分:"+this.sum;
    }
}
public class Work10_2 {

    public static void main(String[] args) throws Exception{
        File f = new File("D:"+File.separator+"STUDENT.txt");
        OutputStream os = new FileOutputStream(f);
        Student[] stu = new Student[5];//具体输入信息的功能交由Student类完成
        for(int i = 0; i<5; i++) {
            stu[i] = new Student();
            byte[] b = new byte[stu[i].toString().length()];
            b = stu[i].toString().getBytes();
            os.write(b); os.write("\n".getBytes());//输入一条记录则换行
        }
        os.close();
    }

}

举报

相关推荐

0 条评论