Issue
initialized the second array dimension but still getting a null pointer exception.
final int LIQUORINV = 8;
final int EACHCOUNT = 10;
Liquor[][] invLiquor = new Liquor[LIQUORINV][EACHCOUNT];
for( int i=0; i <= invLiquor.length; i++){
System.out.println("\nWhich liquor are we counting?");
String type = keyboard.next();
for( int j=0; j < invLiquor[i].length; j++){
invLiquor[i][j].setLiquorType(type);
invLiquor[i][j] = new Liquor();
System.out.println("What is the product name?: ");
invLiquor[i][j].setLiquorName(keyboard.next());
System.out.println("What is the count?: ");
invLiquor[i][j].setLiquorCount(keyboard.nextDouble());
System.out.println("What is the cost?: ");
invLiquor[i][j].setLiquorCost(keyboard.nextDouble());
}
}
I think I did fix this next part however. so that's solved at least.
public static double GetLiquorCostTotal(Liquor[][] inv){
double totalCost = 0;
for( int i=0; i < inv.length; i++){
double sum = 0;
for( int j=0; j < inv[i].length; j++){
sum += (inv[i][j].getLiquorCost() * inv[i][j].getLiquorCount());
}
System.out.println("\nThe total cost of the " + inv[i][0].getLiquorType() +
" inventory is: $" + sum);
totalCost+=sum;
}
return totalCost;
}
Solution
The main issue here is your invLiquor
array. My guess is you want to use invLiquor
to store all the inv
s. In it's current form invLiquor
does not have any association with inv
s. You might want to use a 2D array
of Liquor
, where the row
will be the liquor
categories. Here is a pseudo
code that might be helpful.
// m = category count; n = item in each category;
Liquor[][] invLiquor = new Liquor[m][n];
for(int i=0;i<invLiquor.length();i++){
System.out.println("\nWhich liquor are we counting?");
String type = keyboard.next();
for(int j=0;j<invLiquor[i].length();j++){
invLiquor[i][j].setLiquorType(type);
invLiquor[i][j] = new Liquor();
System.out.println("What is the product name?: ");
invLiquor[i][j].setLiquorName(keyboard.next());
System.out.println("What is the count?: ");
invLiquor[i][j].setLiquorCount(keyboard.nextDouble());
System.out.println("What is the cost?: ");
invLiquor[i][j].setLiquorCost(keyboard.nextDouble());
}
}
double thisLiquorTotal = GetCostTotal(invLiquor);
System.out.println("\nThe total cost of the liquor inventory is: $" + thisLiquorTotal);
// the GetCostTotal method
double GetCostTotal(Liquor[][] invLiquor){
double totalCost = 0;
for(int i=0;i<invLiquor.length();i++){
double sum = 0;
for(int j=0;j<invLiquor[i].length();j++){
sum+=invLiquor[i][j];
}
System.out.println("\nThe total cost of the " + invLiquor[i][0].getLiquorType() +
" inventory is: $" + sum);
totalCost+=sum;
}
return totalCost;
}
This is a simple demo with a fixed number of Liquor
in each category. If you want to have a different number of Liquor
in different categories you might use an Array
of Collections
like LinkedList
or ArrayList
.
Answered By - Tanbir Ahmed