I’m trying to create a list as below in Java. Maybe I’m naive to OOP and Java, therefore I’m not able to resolve it.
I need to create a below table
Character Count Price
A 1 2
B 1 12
C 1 1.25
D 1 0.15
A 4 7
C 6 6
I have create a class as below:
class ProductList {
private char ProductName;
private double Price;
private int Count;
public char getProductName() {
return ProductName;
}
public void setProductName(char productName) {
ProductName = productName;
}
public double getPrice() {
return Price;
}
public void setPrice(double price) {
Price = price;
}
public int getCount() {
return Count;
}
public void setCount(int count) {
Count = count;
}
}
Then comes my main class which create the list of the product table as above.
public class ProductEntryList {
public static void main(String[] args) {
ProductList[] entry = new ProductList[6];
//Product Entry for A
entry[0].setProductName('A');
entry[0].setCount(1);
entry[0].setPrice(2);
//Similarly for other entries of product
for(int loop = 0;loop<entry.length;loop++) {
System.out.print(entry[loop].getProductName()+" ");
System.out.print(entry[loop].getCount()+" ");
System.out.print(entry[loop].getPrice()+"\n");
}
}
}
I’m quite bugged why I m getting
Exception in thread "main" java.lang.NullPointerException
at ProductEntryList.main(ProductEntryList.java:13)
Any input this would be helpful.
Nullpointerexception is thrown when you use dot(.) operator on null reference.
As I can see, In the first line of your main method,
You are only initializing the array, and not initializing the product list entries in the array. So the array contains null entries.
You need to add following code after that line: