user247062
user247062

Reputation: 1

NullPointerException on java array, have created new objects

I'm getting a NullPointerException error when trying to run my program at this part:

File folder = new File("mypictures");
File[] pictures = folder.listFiles();
allCards = new Card[pictures.length];

for(int i=0; i < (pictures.length); i++){
    allCards[i] = new Card(new ImageIcon(pictures[i].getPath())); 
}

It complains on the follow line:

Card[] allCards = new Card[pictures.length];

Upvotes: 0

Views: 64

Answers (2)

user300313
user300313

Reputation: 173

Quite a few things can go wrong in your code. Please use try catch and make sure that folder exists before listing files in the folder.

Upvotes: 0

Mureinik
Mureinik

Reputation: 311188

If folder does not refer to a directory, listFiles() will return null. I.e., when you attempt to call pictures.length, you'll fail with a NullPointerException.

Upvotes: 5

Related Questions