flyf
flyf

Reputation: 13

Cant read back data from csv file into arrays

So i have this code and i'm having trouble retrieving data from my csv file and putting them into an array.

This is what i have on my CSV file

D001,55,Lab,Butch
D002,22,Husky,Ben
D003,12,Maltese,John
D004,34,GermanSheperd,James
D005,76,Rot,Smith
public static void CSVInputFile() throws IOException {

    FileReader inFileReader;
    BufferedReader in;
    String inStr;
    File myFile;
    String dogID;
    int size;
    String breed;
    String name;

    myFile = new File("DogFile.csv");
    inFileReader = new FileReader(myFile);
    in = new BufferedReader(inFileReader);

    inStr = in.readLine();

    Dog[] NewReadDog = new Dog[5];

    int i = 0;
    while (inStr != null) {
        StringTokenizer dogTok = new StringTokenizer(inStr, ",");

        while (dogTok.hasMoreTokens()) {

            dogID = dogTok.nextToken();
            size = new Integer(dogTok.nextToken());
            breed = dogTok.nextToken();
            name = dogTok.nextToken();
            NewReadDog[i] = new Dog(dogID, size, breed, name);
            i++;
            System.out.println("dog " + i + " is stored");
        }
    }

    System.out.println("\nOutput Dogs from CSV FILE: ");

    for (int count = 0; count < NewReadDog.length; count++) {
        System.out.println(NewReadDog[count]);

    }

    in.close();

}

I'm just starting to learn coding so please bear with me. thanks

Upvotes: 1

Views: 53

Answers (1)

Rene8888
Rene8888

Reputation: 199

You have to read the next line when finished tokenizing the current one:

while (inStr != null) {
    StringTokenizer dogTok = new StringTokenizer(inStr, ",");

    while (dogTok.hasMoreTokens()) {
        [...]
    }
    System.out.println("dog " + i + " is stored");
    inStr = in.readLine();
    i++; //replaced here 
}

Upvotes: 2

Related Questions