首页 > 解决方案 > 从文件创建对象的数组列表

问题描述

我有两节课StudentStudents

如何在不使用变量保存下一行并将其转换为所需数据类型(即转换为)的情况下将文件读入student数组列表以创建对象。studentStringint

public class Student
{
    private String name;
    private int age;
    private double gpa;

    public Student(String person, int years, double avg)
    {
        // initialise instance variables
        name = person;
        age = years;
        gpa = avg;
    }

    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return age;
    }
    public double getGPA()
    {
        return gpa;
    }

public class Students
{
    private ArrayList<Student>students;

    public Students()
    {
        // initialise instance variables
        students = new ArrayList<Student>();
    }
    public void add(Student s)
    {
        students.add(s);
    }
    public Student readFile() throws IOException
    {
        // reads data file into ArrayList
        String line;
        Scanner sc = new Scanner(new File("Students.txt"));
        while (sc.hasNextLine()) {
         **//code to read file into student array list**
        }
        sc.close();
    }

我试图从中读取的文件

Name0
22
1.2
Name1
22
2.71
Name2
19
3.51
Name3
18
3.91

请不要标记为重复或类似的问题。我已经广泛搜索了类似于我想要实现的已回答的问题,但没有找到任何对我有用的问题。

标签: javaoopbluej

解决方案


要从文件中获取字符串,您可以调用 Scanner.nextString():因为您的扫描仪对象称为 sc,所以它看起来像 sc.nextString()。要获取 int,可以调用 Scanner.nextInt(),要获取 double,可以调用 Scanner.nextDouble()。

您不想将这些存储在中间值中,而是想立即创建一个学生值。您可以在 Student 构造函数中放入任何您想要的内容,只要您放入的第一件事的计算结果为 String,第二个计算结果为 int,第三个计算结果为 double。由于您的文件总是有一个 String 然后是一个 int 然后是一个 double,我认为您可以使用我上面列出的方法,并调用 Student 构造函数来获取一个 Student 值。


推荐阅读