0

I currently need to import data from a CSV file into an array as an object. The data is not all of the same type however and one line of the data is formatted like this "Tom, Jones, 95846, 657.45". I am able to parse the file but cannot seem to figure out how to store this data into an array. I will need to sort this data later on based on different requirements like Name and Number.

import java.io.*;
import java.util.*;


public class People {

public static void main(String[] args) {
    File file = new File("People.csv");

    People peopleArr[] = new People[100];

    try{
        Scanner inputFile = new Scanner(file);
        inputFile.useDelimiter(",");

        while(inputFile.hasNext()){
     // Store the data into array

        }
        inputFile.close();

    }catch (FileNotFoundException e){
        System.out.println("Check file");
    }

}

}
  • Possible duplicate of [reading a csv file into a array](https://stackoverflow.com/questions/40074840/reading-a-csv-file-into-a-array) – mbozwood Sep 10 '17 at 00:14
  • I just tried that method and since I'm not using ArrayList, I'm assuming that my code is messing up at the "Arrays.asList" line. – user162232 Sep 10 '17 at 00:26

1 Answers1

0

Maybee smth like this:

public static People[] readPeople(File file) {
    List<People> people = new ArrayList<>(100);

    try (Scanner inputFile = new Scanner(file)) {
        inputFile.useDelimiter(",");

        while (inputFile.hasNext()) {
            People obj = new People();
            // e.g. line is equals to John,Done
            // obj.setFirstName(inputFile.next());
            // obj.setLastName(inputFile.next());
            people.add(obj);
        }
    } catch(FileNotFoundException e) {
        System.out.println("Check file");
    }

    return people.toArray(new People[people.size()]);
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35