Why did I get an "ArrayIndexOutOfBoundsException"?
Your issue is clearly with the use of i
, as that is the only variable index on that line, and the out of range index is "15", which is just past the end of your 15-item array. So, couple of issues, all surrounding the use of i
:
As nhellwig mentioned, be sure that i
is actually initialized to 0 before calling this function.
Additionally, you're putting a lot of faith in the consistency of the item number in the file and the actual number of items. You should either produce a warning and stop trying to store items in the array if i >= itemCount
, or use a container like an ArrayList that can grow to accommodate new items instead of a fixed size array.
Edit: Also, I should point out that you increment i
whether you read an item or not, which means even blank lines will increment i
, causing gaps in your list or array overruns. Since itemCount
is the number if items, you should stick to that and only increment i
if you read an actual item.
In that same spirit, you should verify that invData.length == 5
after you call split(), because a misplaced comma, etc. in your file may also end up with an OOB error. Granted, for your project, it's probably OK to make assumptions about the number of elements in a line that starts with "produce" or "cleaning", but in general it's important to be cautious with data coming from a user-created file.
I found the answer to be that I needed an "s.nextLine();"
Because I used "s.nextInt();" the pointer was just hangin around at the end of "15" in my file. Then, when the first line in the While loop "String line = s.nextLine();" executed the pointer moved from the end of 15 to before the p in produce in the 2nd line of the list file.
The working method looks like this:
public void readFile(String fileName){ try{ File invList = new File (fileName); Scanner s = new Scanner(invList); int itemCount = s.nextInt(); s.nextLine(); // This is the new line that made it work list = new Product[itemCount]; count = itemCount; while (s.hasNext()){ String line = s.nextLine(); //moves file pointer over one invData = line.split(","); if (invData[0].equals("produce")){ list[i] = new Produce(invData[1], invData[2], invData[3], invData[4]); } else if(invData[0].equals("cleaning")){ list[i] = new Cleaning(invData[1], invData[2], invData[3], invData[4]); } i++; }//end of while loop } catch (FileNotFoundException Abra) { String error = Abra.getMessage(); System.out.println(error); } } // end of method