hi I'm working on my hw and I have problem
I know how to read file from data and split each line using array

now I want to use arrayList .. I want to read the data from the file and create arrayList and then split each line and create object of type student
the file contanin id,program,gpa

I have Student class and the main form
in the student class I have format method , get and set methods

and this constructor

public Student(int id, String program, double gpa) {
        this.id = id;
        this.program = program;
        this.gpa = gpa;

//this is my main form 

package hw;

import java.util.ArrayList;
import java.util.List;
import utilities.FileUtils;

public class JFrameHw extends javax.swing.JFrame {

    List<Student> student = new ArrayList();

    public JFrameHw() {
                student = createStudent(txtFile.getText());


// This is my method 

 public List<Student> createStudent(String fileName) {
        String[] data = FileUtils.readIntoArray(fileName);
        List<Student> res = new ArrayList();
        for (int i = 0; i < student.size(); i++) {
            Student line = student.get(i);
            //Student line = (Student) list;

        return res;

4 Years
Discussion Span
Last Post by mvmalderen
Featured Replies
  • 2

    In addition: don't forget to [close the file](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html). Read More


Here, maybe this can help you:

    public void loadStudentsFromFile(){
        BufferedReader in = null;
            in = new BufferedReader(new FileReader(filename));
            String line;
            while ((line = in.readLine()) != null){
                String tokens[] = line.split(",");
                studs.add(new Student(Integer.parseInt(tokens[0]),tokens[1], Double.parseDouble(tokens[2])));
        } catch (IOException e){

where studs is:

private ArrayList<Student> studs = new ArrayList<Student>();

As a simple testing stuf:
Having in your Student class a function toString() like this:

    public String toString(){
        return new String("Id: "+Integer.toString(id)+", Program: "+program+", GPA: "+Double.toString(gpa));

and a filename containing this:


would provide this output (if you use to print all the elements from the array using the toString() function):

Id: 1, Program: Program1, GPA: 5.6
Id: 2, Program: Program2, GPA: 6.7
Id: 3, Program: Program3, GPA: 7.9

And the printing function, easilly put:

    public void showStudents(){
        for (Student i:studs) System.out.println(i.toString());

Edited by Lucaci Andrew

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.