从文件创建对象数组列表

Create an array list of objects from a file

我有两个类StudentStudents

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

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

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

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

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

import java.util.List;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;

public class Students
{
    public static void main(String[] args){
        List<Student> students = new ArrayList<Student>();
        File file = new File("C:\Users\Nik\Desktop\test.txt"); //Update path
        int i = 0;  
        BufferedReader br;
        try {
            br = new BufferedReader(new FileReader(file));


            String line;
            Student student = new Student();
            while ((line = br.readLine()) != null) {
                if(i%3 == 0){
                    student = new Student();
                    student.setName(line);
                } else if (i%3 == 1){
                    if(line != null && !line.isEmpty() && isNumber(line)){
                        student.setAge(Integer.parseInt(line));
                    }
                } else if(i%3 == 2){
                    if(line != null && !line.isEmpty() && isNumber(line)){
                        student.setGpa(Double.parseDouble(line));
                    }
                    students.add(student);
                }   
                i++;
            }

            for(Student x:students){
                System.out.println(x.toString());
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }

    static boolean isNumber(String s){
        return s != null && s.matches("[-+]?\d*\.?\d+");  
    }   
}   



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 Student() {

    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getGpa() {
        return gpa;
    }

    public void setGpa(double gpa) {
        this.gpa = gpa;
    }

    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + ", gpa=" + gpa + "]";
    }
}

这样试试

public Student readFile() throws IOException
        {
            // reads data file into ArrayList
            String line;
            Scanner sc = new Scanner(new File("Students.txt"));
            while (sc.hasNextLine()) {
             Student student = new Student(sc.nextLine(), Integer.parseInt(sc.nextLine()), Double.parseDouble(sc.nextLine()));
            }
            sc.close();
        }