I have the following two classes:
import java.io.*;
import java.util.*;
public class User {
public static String nickname;
public static String ipAddress;
public static ArrayList<String> listOfFiles;
public static File sharedFolder;
public static String fileLocation;
public User(String nickname, String ipAddress, String fileLocation) {
this.nickname = nickname.toLowerCase();
this.ipAddress = ipAddress;
Scanner userTyping = new Scanner(System.in);
fileLocation = userTyping.nextLine();
sharedFolder = new File(fileLocation);
}
public static List<String> fileList() {
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()));
System.out.println(listOfFiles.get(i));
}
return listOfFiles;
}
@Override
public String toString() {
return nickname + " " + ipAddress;
}
}
and the next one:
import java.util.*;
public class UserCollector {
static List<User> allUsers;
public static void addUserToTheList() {
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Type nickname: ");
String nickname = keyboardInput.nextLine();
System.out.println("Type IP: ");
String ipAddress = keyboardInput.nextLine();
System.out.println("Type File Location: ");
String fileLocation = keyboardInput.nextLine();
System.out.println("User that is attempting to log in is: "+ nickname + " and his IP is: " + ipAddress);
User inputUser = new User(nickname, ipAddress, fileLocation);
allUsers = new ArrayList<User>();
if (keyboardInput.nextLine().equalsIgnoreCase("INSERT") && !allUsers.contains(inputUser)) {
allUsers.add(inputUser);
System.out.println("User has been successfully added to your list.");
}
else
System.out.println("This user already exists on the list!");
}
public static void currentStateOfTheList() {
for (User u : allUsers) {
System.out.println("nick: "+u.nickname +", ip: "+ u.ipAddress );
}
}
public static void main(String[] args) {
UserCollector.addUserToTheList();
UserCollector.currentStateOfTheList();
}
}
Now, the idea for the addUserToTheList() method is simple. Add objects of type User into the ArrayList. And also do so by typing nickname, ipAddress and fileLocation into the console. First time I ran it, it worked fine but it threw an Exception (NullPointer). Now when I run it, it compiles fine but it says that I already have that user in the list although I always give different nickname/ipAddress/fileLocation.
I believe there is something wrong with User object that probably stays the same every time I try to run it.
I hope someone helps me. Thanks