Skip to content
Advertisement

How to add items to array of objects using loops

I’ve got a multiple student objects I want to write into with a CSV file containing their details. I’ve set each row of the CSV file to an array then was going to split each entry of the array into another array and use that to set the attributes of the object. However, each time I try, I get a NullPointerException.

String studentCSV = "src\CSV Files\Students.csv";
Student[] student = new Student[CSV_Reader.count(studentCSV)];
String[] values = CSV_Reader.read(studentCSV);

for(int i=0;i<values.length;i++){
    String[] line = values[i].split(",");
    student[i].addPerson(line[0],line[1],line[2],line[3]);
    student[i].addStudent(line[4],line[5],line[6]);
}

Advertisement

Answer

int n=10; // for example
Student[] student = new Student[n];
//now you just allocate memory for array

for(int i=0;i<student.length;i++){
    student[i]=new Student(); 
// here you assign student to your any element of array  
}
// now you can do anything with  elements of your student array
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement