samedi 6 décembre 2014

NullPointerException on getter


Vote count:

0




I am working on a class final. It is supposed to be a "Media Library" to stores information about a persons media(DVDs, games etc.) among other things it's supposed to take in new media items, store them to an array and display them when prompted. It does all of those but when it displays it has a NullPointerException on the getters even though it is executing it how I intended.



public class MediaItem {
private String title;
private String format;
private boolean onLoan;
private String loanedTo;
private String dateLoaned;

public MediaItem(){
title = null;
format = null;
onLoan = false;
loanedTo = null;
dateLoaned = null;

}

public MediaItem(String title, String format){
this.title = title;
this.format = format;
onLoan = false;

}


Above are the fields and constructors for the class that makes the "MediaItems" as we were told to call them


Below, parts of another class, that is the library itself. One array for storing the media items and one for printing out the list. Also the add method and how I have been adding them to the array.



private MediaItem[] items = new MediaItem[100];
private String[] listOfItems = new String[100];
private int numberOfItems = 0;

public void addNewItem(String title, String format){
MediaItem item = new MediaItem(title, format);
items[numberOfItems] = item;
numberOfItems++;
}


And here is the part I am having problems with



public void listAllItems(){
for (int i = 0; i < items.length; i++){
System.out.println(items[i].getTitle());
}
}


This isn't what its supposed to do, but my current problem is that it does print out the entire list of items but also gives a NullPointerException and I dont know why. The getter that is being called is a basic eclipse generated getter



public String getTitle() {
return title;
}


This is a Java I coarse so I'm new so please be gentle. I believe that is all the relevant parts so any help is appreciated!



asked 1 min ago







NullPointerException on getter

Aucun commentaire:

Enregistrer un commentaire