I am new to programming and task assignment for a class. Now I am not asking anyone to write my code for me, but I am stuck with a runtime error. In the task, we need to read the file, use the first line "15" to initialize the size of the array and proceed to filling the array with information from each line.
edit: I didnโt want to publish all the code because I thought it would look too long, but due to the fact that downvotes will be vague, here it is.
File:
15 produce,3554,broccoli,5.99,1 produce,3554,broccoli,5.99,1 produce,3555,carrots,2.23,0.25 produce,3555,carrots,2.23,0.25 produce,3555,carrots,2.23,0.25 cleaning,2345,windex,5.99,1 unit cleaning,2345,windex,5.99,1 unit cleaning,2345,windex,5.99,1 unit cleaning,2345,windex,5.99,1 unit cleaning,2346,toilet paper,12.99,4 rolls cleaning,2346,toilet paper,12.99,4 rolls cleaning,2335,windex,2.25,1 mini sprayer cleaning,1342,wipes,3.99,10 units cleaning,1342,wipes,3.99,10 units produce,3546,lettuce,2.99,0.5
My mistake:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15 at Inventory.readFile(Inventory.java:45) at Inventory.<init>(Inventory.java:12) at Supermarket.main(Supermarket.java:3)
Class with line 45 in question (line 45 commented, scroll right) "
import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; public class Inventory{ Product[] list; String[] invData; private int i = 0; public int count; public Inventory (String f){ readFile(f); } public int indexOfProduct(int code){ for(i=0; i<list.length; i++){ if (list[i] != null) if (list[i].getCode() == code) return i; } return -1; } public Product delete(int pos){ Product temp = new Product(); temp = list[pos]; list[pos] = null; return temp; } public void readFile(String fileName){ try{ File invList = new File (fileName); Scanner s = new Scanner(invList); int itemCount = s.nextInt(); list = new Product[itemCount]; count = itemCount; while (s.hasNext()){ String line = s.nextLine(); invData = line.split(","); if (invData[0].equals("produce")){ list[i] = new Produce(invData[1], invData[2], invData[3], invData[4]);
Why did I get an "ArrayIndexOutOfBoundsException"? I hope someone can point out a flaw in my logic, so I do not repeat it again.