Search code examples
javaoopbluej

Create an array list of objects from a file


I have two classes Student and Students

How can I read the file into the student array list to create student objects without using a variable to hold the next line and convert it to the required data type(i.e. String to int).

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

File I am trying to read from

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

Please, do not mark as duplicate or similar question. I have searched extensively for answered questions similar to what I am trying to achieve but have not found any that will work for me.


Solution

  • To get a String from the file, you can call Scanner.nextString(): since your scanner object is called sc, that would look like sc.nextString(). To get an int, you can caller Scanner.nextInt(), and to get a double, you can call Scanner.nextDouble().

    You do not want to store these in intermediate values, but instead want to create a student value right away. You can put whatever you want in your Student constructor, as long as the first thing you put evaluates to a String, the second evaluates to an int, and the third evaluates to a double. Since your file always has a String then an int then a double, I think you can use the methods I listed above, and make a call to the Student constructor, to get a Student value.