Can't seem to get rid of the error, look at different methods of getting rid of it, but can't really understand.
static Holding[]holding = new Holding[15];
public static void main(String[] args){
sampleData(); //Sample Data from Assignment
int options;
do{
scanner = new Scanner(System.in);
System.out.println("1. Add Holding");
System.out.println("7. Print all Holdings");
System.out.println("13. Exit");
options = scanner.nextInt();
switch(options){
case 1:
addHolding();
break;
case 7:
printHolding();
break;
default:
System.out.println("Please");
}
}while(options != 13);
System.out.println("I'm out");
}
public static void sampleData(){
holding[0] = new Book("b000001", "Intro to Java");
holding[1] = new Book("b000002", "Learning UML");
holding[2] = new Book("b000003", "Design Patterns");
holding[3] = new Book("b000004", "Advanced Java");
holding[4] = new Video("v000001", "Java 1", 4);
holding[5] = new Video("v000002", "Java 2", 6);
holding[6] = new Video("v000003", "UML 1", 6);
holding[7] = new Video("v000004", "UML 2", 4);
}
public static void printHolding(){
int option;
do{
for(Holding h : holding){
h.print();
System.out.println();
}
System.out.println("To exit press '0'");
option = input.nextInt();
}while(option != 0);
}
Exception in thread "main" java.lang.NullPointerException
at s3599741_A2.LibraryMenu.printHolding(LibraryMenu.java:307)
at s3599741_A2.LibraryMenu.main(LibraryMenu.java:71)
The error is
h.print();
and
printHolding();
in the switch statement. As you can see, the array is made from another object, like
holding[i] = new Book("Insert ID", "Insert Title");
I wrote a question like this but got marked as duplicate, I looked at the link
What is a NullPointerException, and how do I fix it?
But can't find the problem I have or that I don't have the knowledge yet to understand. Can someone explain what I should do?
The limit of the Holding must be 15, I cannot use ArrayList or List.
The Holding Class:
public abstract class Holding{
private String holdingId;
private String title;
public Holding(String holdingId, String title){
this.holdingId = holdingId;
this.title = title;
}
public String getId() {
return holdingId;
}
public String getTitle(){
return title;
}
public boolean getStatus(){
return active;
}
public void print(){
System.out.println("ID: " + getId());
System.out.println("Title: " + getTitle());
}
}