0

I'm pretty new to Java (currently enrolled in my first programming class), so the answer to my question could be right in front of me.

My goal is to read in a text file that reads as follows:

4563123,112211324135412
2312311,222121324135211
2312345,112211324135421
5527687,212111313124412
7867567,111111111111111

where the first set of numbers is an ID, and the second set is a set of answers to a test (of which I have the key). Once I've read in the answers I need to store them in an array (and I assume just an array, as my class has not covered ArrayLists yet). All of this data would need to be stored in one array, since I need to return it at the end of the method.

Here is the code that I have so far:

public static String[] readFile(String filename)throws IOException{
    Scanner inFile = new Scanner(filename);
    String line;
    String[] results = new String[101];
    int i = 0;
    while (inFile.hasNextLine()){
        line = inFile.nextLine();
        String[] incoming = line.split(",");
        String wid = incoming[0];
        String answer = incoming[1];
        results[i] = wid;
        results[i + 1] = answer;
        i += 2;

    }
    inFile.close();
    return results;
}

It's safe to ignore the String filename, it was passed in from the main.

Every time I run this method, I keep running into an ArrayOutOfBoundsException, mainly when I try to assign incoming[1] to answer.

I've been staring at this code longer than what is probably good for me, but it seems that I just can't wrap my head around it. Any help would be appreciated, whether that be telling me what is wrong or what I can do to improve.

2
  • 3
    if there is a newline at the end of your text file then line.split(",") will not split the line, therefore array index position 1 would be out of bounds because it does not exist Commented Mar 17, 2014 at 17:12
  • Are you using Java 7? Commented Mar 17, 2014 at 17:13

2 Answers 2

1

Since you are using Java 7, use the new Files API and a try-with-resources statement; also, avoid copying empty lines:

final Path file = Paths.get(filename);
String line;
String[] incoming;
String[] results = new String[101];
int nrElements = 0;

try (
    final BufferedReader reader = Files.newBufferedReader(path,
        StandardCharsets.UTF_8);
) {
    while ((line = reader.readLine()) != null) {
        incoming = line.split(",");
        if (incoming.length != 2)
            continue;
        results[nrElements++] = incoming[0];
        results[nrElements++] = incoming[1];
    }
}

return Arrays.copyOfRange(results, 0, nrElements);
Sign up to request clarification or add additional context in comments.

6 Comments

I'm afraid that I'm very unfamiliar with most of this solution. While I understand the logic behind it, I've never used a BufferedReader, or even a try statement. The programming that we're doing is supposed to be somewhat basic (the professor just taught how to read in text last week), but for some reason I've hit this roadblock. I will do some further reading on some of the code that you've posted, it definitely looks like an easier way of going about things.
try () {} is a try-with-resources statement; you declare the resources to open in (), the code using these resources in {}, and Java will automatically close the sources for you -- whether the code in {} throws an exception or not. This is basic Java 7 stuff ;) See a small writeup on Java 7 and files here
thank you so much! Also, one last question. Is it possible to clip off the rest of the array so I don't have a bunch of nulls, or is it even necessary? The array is supposed to work for "any number of students", up to a maximum of 50 (hence the size of the results string in my code.
It is, but first of all, do you have to use an array? Can't you use an ArrayList for instance? The trick here is to retain the number of elements you have written (you already do here) and use Arrays.copyOfRange(). Or, if you just have to print it, loop over the elments of the array and stop when you read one null.
I actually don't need to print it, when I asked before it was just my way of checking. This array will end up being passed into other methods to be used. We're covering ArrayLists in a couple of weeks, so I'm not sure if the solution explicitly requires it, not to mention my lack of knowledge on how to properly use and read from them. I just wasn't sure if the nulls in the array would have an impact on the array's use in other methods at all.
|
0

Either you are having an empty line in your file. Or a garbage line that doesn't have any comma in it. So before accessing the slitted array, just give a check.

if(incoming != null && incoming.length >= 2){
    String wid = incoming[0];
    String answer = incoming[1];
    // ... other dependent codes go here!
}

It will help you to avoid the Exception.

2 Comments

Okay, no Exception now, however when I tried to print the Array to check if it stored everything, it prints out: [Ljava.lang.String;@4c56291a
How did you print it? Use Arrays.toString(yourArrayReference);, or write your own print method for further needs.

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.