I have a class User that contains attributes: nickname, ipAddress, sharedFolder. The idea is to have a user with these attributes and a list of files from a shared folder.
This is my code:
import java.io.*;
import java.util.*;
public class User {
String nickname;
String ipAddress;
static ArrayList<String> listOfFiles;
File sharedFolder;
String fileLocation;
public User(String nickname, String ipAddress, String fileLocation) {
this.nickname = nickname.toLowerCase();
this.ipAddress = ipAddress;
sharedFolder = new File(fileLocation);
File[] files = sharedFolder.listFiles();
listOfFiles = new ArrayList<String>();
for (int i = 0; i < files.length; i++) {
listOfFiles.add(i, files[i].toString().substring(fileLocation.length()));
}
}
public static void showTheList() {
for (int i = 0; i < listOfFiles.size(); i++) {
System.out.println(listOfFiles.get(i).toString());
}
}
@Override
public String toString() {
return nickname + " " + ipAddress;
}
public static void main(String[] args) {
showTheList();
}
}
However, when I run it I can’t get the list of files. It throws an exception:
Exception in thread “main”
java.lang.NullPointerException
at User.showTheList(User.java:35)
at User.main(User.java:52) Java Result: 1
I know it’s probably a tiny little mistake but I can’t seem to fix it 🙁
Please help.
listOfFilesbeing a static field should be initialized in a static block, not constructor.i.e.
or you can also initialize it at the site of declaration itself.
i.e.
In your code, you are not creating any object of the class and hence
listOfFilesreference is never assigned anArrayListinstance. That’s the reason you’re getting aNullPointerException.