In my program, I create an attraction and fill out the number of ticket types, is title and cost, and then I exit the program and run it again.
I have a constructor that reads elements from a file. When I then try to read an array element, it gives me a NullPointerException
error even though the element is not null.
When I comment out the code block below where the error is located, I get a NumberFormatException
error instead for the input string, "Tour Only", so I know it's not null.
fileScanner.nextLine();
for (int i = 0; i < getTicketTypesNum(); i++)
this.ticketTypeTitle[i] = fileScanner.nextLine();
fileScanner.nextLine();
The code in full is below.
Attraction.java
// The constructor.
public Attraction(Scanner fileScanner) {
...
// The data read before the error.
fileScanner.nextLine();
this.ticketTypesNum = Integer.parseInt(fileScanner.nextLine());
fileScanner.nextLine();
fileScanner.nextLine();
for (int i = 0; i < getTicketTypesNum(); i++) {
// Line where the error is located.
this.ticketTypeTitle[i] = fileScanner.nextLine();
}
fileScanner.nextLine();
for (int i = 0; i < getTicketTypesNum(); i++)
this.ticketTypeCost[i] = Integer.parseInt(fileScanner.nextLine());
fileScanner.nextLine();
...
}
// Store the attraction information and write it to file.
public void writeData(PrintWriter pw) {
...
pw.println("Number of Ticket Types:");
pw.println(getTicketTypesNum());
pw.println();
pw.println("Ticket Titles:");
for (int i = 0; i < getTicketTypesNum(); i++)
pw.println(getTicketTypeTitle()[i]);
pw.println();
pw.println("Ticket Costs:");
for (int i = 0; i < getTicketTypesNum(); i++)
pw.println(getTicketTypeCost()[i]);
pw.println();
...
}
If you need more code, I'll edit my question to include more.
Thank you for your help!
UPDATE
I tried commenting out the line where I had the error out and continued running the code, and I get a NullPointerException whenver I have to read an array element.