2

I've been trying to read from a csv file and fill an array of State objects, but the array never gets filled past the 1st ([0]) index. The format of the csv file is like this:

Mississippi,Jackson,MS,2991207,South,4
New Hampshire,Concord,NH,1323459,New England,2

where each set of data is separated by a new line.

inFile.useDelimiter(",|\n");
    String headerLine  = inFile.nextLine();
    for(int i = 0; i<50; i++) {
        while(inFile.hasNext()) {
            State state = new State(inFile.next(), inFile.next(), inFile.next(), inFile.nextInt(),
                              inFile.next(), inFile.nextInt());
            stateArray[i] = state;
        }
    }

This is my code for populating the array of States with elements. It uses a Scanner called inFile to parse the csv. I'm not sure how else to do this. I've tested with print statements, and only the first index of the stateArray ever has any fields filled in it.

System.out.println(stateArray[0].GetStateName());

for example, returns "Mississippi", but any other index results in a Null Pointer Exception.

2 Answers 2

2

You have a while loop inside of your for loop. The while loop will continue to execute until you have read the entire infile and in addition it will just continue to overwrite the stateArray[0] index.

There are a few options for handling this file line by line.

One thing you can do is use two separate scanners.

for (int i = 0; i < 50 && infile.hasNextLine(); i++) {
    String line = infile.nextLine();
    Scanner stateLine = new Scanner(line);
    stateLine.useDelimiter(",");
    try {
        stateArray[i] = new State(stateLine.next(), stateLine.next(), stateLine.next(), stateLine.nextInt(), stateLine .next(), stateLine.nextInt());
    } catch (Exception e) {
        e.printStackTrace();
        // This is optional, just there so you can see why your input is throwing an error.
    }
    stateLine.close();
}

There are other solutions available as well, you may want to consider if your input is guaranteed to be in the correct format or if there may be variable formats and file lengths.

Sign up to request clarification or add additional context in comments.

1 Comment

This one is fully true, so set the answer as true please!
1

Maybe try using a library to read this as your solution will fail if any value contains a comma (you will split it into 2 unintentionally).

Here's my implementation using univocity-parsers:

Put a few @Parsed annotations in the fields of your State class. I don't know what the field names are so I just made up the attribute names and assigned a position to each one.

public class State {
    @Parsed(index = 0)
    String name;
    @Parsed(index = 1)
    String city;
    @Parsed(index = 2)
    String acronym;
    @Parsed(index = 3)
    String postcode;
    @Parsed(index = 4)
    String conty;
    @Parsed(index = 5)
    int id;
}

Now, to parse your file into a list of State objects, just do this:

List<State> states = new CsvRoutines().parseAll(State.class, new File(inputFile), "UTF-8");

Hope it helps.

Disclosure: I'm the author of this csv parsing library. It's open source and free (Apache 2.0 license).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.