Reputation: 59
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
Upvotes: 0
Views: 60
Reputation: 68715
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
Upvotes: 4