Op-Zyra Op-Zyra - 1 year ago 95
Java Question

Please help, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9

public class ItemTable {
private final Integer[] idT = { 1,2,3,4,5,6,7,8,9,10 };
private final Integer[] quantityT = { 1,2,3,4,5,6,7,8,9,10 };

private final String[] barcodeT = { "001" , "002", "003", "004", "005",null,null,null,null,null, };
private final String[] nameT = { "Milk", "Bread", "Wine", "Butter", "Potato", "Sweet Potato","Ginger" ,"Avacado", "Cucumber"};
private final double[] perWeightT = {0.2,0.4,0.1,0.2,0.1,2,1,0.5,0,0,0};
private final double[] perPriceT = { 1.50, 2.45, 12.95, 4.75, 2, 3.5, 12, 4, 3, 1 };

private final ArrayList<ItemType> table = new ArrayList<>();
public final ArrayList<View> lookUpItem = new ArrayList<>();

public ItemTable()
for(int i = 0; i< idT.length; i++)
table.add(new ItemTypeB (idT[i], nameT[i], perPriceT[i],perWeightT[i],barcodeT[i]));
table.add( new ItemTypeW(idT[i], nameT[i], perPriceT[i],perWeightT[i],perWeightT[i]));
lookUpItem.add( new View(idT[i], nameT[i], "w"));
table.add( new ItemTypeC(idT[i], nameT[i], perPriceT[i],perWeightT[i], quantityT[i] ));
lookUpItem.add( new View(idT[i], nameT[i], "c"));



The problem area is specifically at table.add( new ItemTypeC) around the last line of codes,
been stuck here for ages and not sure why.. please help

Answer Source

One of your arrays (nameT) is "one-off"; meaning: all your arrays have 10 elements, but that has only 9 members.

But the actual problem is of a different nature: you are doing something very wrong here. Your program is written in "procedural" style.

Meaning: you have various elements that "together" form something meaningful. Your implementation: put each of those elements into its own array; and fetch the values from each array to "build" the thing that they are supposed to mean "together". So the thing that constitutes your "entity" ... is just the index within 5 different arrays.

In an Object Oriented approach, you create abstraction. Like a class Product, which has a variety of properties; such as "id", "quantity", "name" and so on. This also allows you to create reasonable equals methods to easily figure if two products are the same. And when you have created such a class; then you create one array of such objects.

Long story short: programming in Java is about finding and creating good abstractions. If you don't do that ... you run exactly in such kind of low-level problems.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download