Java笔试题-C盘下面有一个aa.txt的文件,文件里存放了年级每一个学生的成绩,格式为:姓名 分数 班级...

本文介绍了一个Java程序示例,该程序用于从文本文件中读取学生的成绩信息,并使用自定义的Student类来存储这些信息。通过BufferedReader逐行读取文件,解析每一行数据,提取姓名、分数和班级等字段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:C盘下面有一个aa.txt的文件,文件里存放了年级每一个学生的成绩,格式为:姓名 分数 班级如:

张三80 1班

李四90 2班

设计一个方法,读取文件里的信息,最后输出学生的信息,输出格式为:姓名:张三 分数:80 班级:1班

要求:使用类存储每一行学生信息,使用list存储所有的学生信息。

public class ReadTextLine {
public static void main(String[] args) throws IOException {
    List<Student> list=getReader("E:\\score.txt");
    System.out.println(list);
    for(Student s:list){
        System.out.println("姓名:"+s.getName()+" "+"分数:"+s.getScore()+"班级:"+s.getCls());
    }
}
public static List<Student> getReader(String path) throws IOException{
     List<Student> students=new ArrayList<Student>();
    FileInputStream in=new FileInputStream(new File(path));
    InputStreamReader inr=new InputStreamReader(in);
    BufferedReader buf=new BufferedReader(inr);
    String s="";
    while((s=buf.readLine())!=null){
        Student student=new Student();
        int index=s.indexOf(" ");
        student.setName(s.substring(0,index-2));
        student.setScore(Integer.parseInt(s.substring(index-2,index)));
        student.setCls(s.substring(index,s.length()));
        students.add(student);
    }
    in.close();
    buf.close();
    inr.close();
    return students;
}
}

存储类:

public class Student {
    private String name;
    private int score;
    private String cls;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public String getCls() {
        return cls;
    }

    public void setCls(String cls) {
        this.cls = cls;
    }

}

利用IO流读取文件信息:file-->FileInputStream-->InputStreamReader-->BufferedReader在通过while循环将每一行数据取出,每一次取出将其放入一个临时的String中,当为null时停止

将每一行数据通过空格分隔,空格以后的为班级,空格前两个为成绩,2位数,0到空格-2为姓名

转载于:https://www.cnblogs.com/ys15/p/11525449.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值