Upon checking for Null values in a 2D array, do I keep getting the java.lang.NullPointerException
error?
Here's my 2D array:
String[][] userInfo = new String[10][4];
Here's a method for deleting an entire entry in the array based on user input:
private void removeUser(String userInfo[][]) {
String first = "";
String last = "";
Scanner searchUserinput = new Scanner(System.in);
String searchUser;
System.out.println("Which user would you like to search for? Please enter their first and last name");
searchUser = searchUserinput.nextLine();
/*System.out.println(searchUser); */
String[] words = searchUser.split("\\s+");
if (words.length > 2) {
System.out.println("Please enter only the first and last name");
}
else {
for (int i = 0; i < words.length; i++) {
first = words[0];
last = words[1];
}
}
outerloop:
for (int row = 0; row < userInfo.length;) {
for (int column = 0; column < userInfo[row].length;) {
if (userInfo[row][column]!= null) {
if (userInfo[row][0].equals(first) && userInfo[row][1].equals(last)) {
System.out.println("We found this user's contact info the database.");
System.out.println("Removing now...");
userInfo[row][0] = null;
userInfo[row][1] = null;
userInfo[row][2] = null;
userInfo[row][3] = null;
break outerloop;
}
else{
column ++;
row ++;
break;
}
}
}
row++;
}
}
Let's say I have a number of rows and columns with data, like this:
Bill Smith 123 123 Jon Dude 234 23 Another Guy 2332 435 Some Person 1212 12
If I try to delete say Bill Smith
, there's no error thrown, or if I try to delete Another Guy
, still no issue. But If I, for example, delete Bill Smith
, then try to delete Jon Dude, that's why I get the error. But Java is telling me the error is from the very line wherein I'm checking for a null value with: if (userInfo[row][column]!= null)
, not understanding why.
Exception in thread "main" java.lang.NullPointerException
at Lab02.removeUser(Lab02.java:96)
at Lab02.<init>(Lab02.java:32)
at Lab02.main(Lab02.java:5)
Line 96 is where if (userInfo[row][column]!= null)
is in the full script.