0

I am trying to search through a file to print out scores. Here is what I have:

 while (input.hasNextLine()) {
        String record = input.nextLine();
        String[] field = record.split(" ");
        if(field[1].equals(targetState)) { 
            System.out.print(field[0] + ": ");
            System.out.println(field[2]);
        }
    }

And the data in file looks like this:

2007,Alabama,252

When I ran this code, I get that java.lang.ArrayIndexOutOfBoundsException error. I just wonder what is wrong with the code

Thanks

2
  • 1
    Or just read the exception. It tells you the index, the size of the collection, and the line where it occurred ... Commented Apr 4, 2014 at 0:32
  • Right -- read the very excellent exception. It tells you exactly what's wrong and where. Commented Apr 4, 2014 at 0:57

1 Answer 1

4

You need to split using comma and not space. Change this

    String[] field = record.split(" ");

to

   String[] field = record.split(",");

As you don’t have the spaces in your input string, so it is not getting split and hence the output array does not have multiple items, leading to ArrayIndexOutOfBoundException

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.