0

I'm trying to make a for loop that loops through an array, comparing the user input to each object using a method called getID() that returns the stored user IDs for various employees. The data is not saved between runs, so on the first loop, all objects (I believe) should be null. With that being said, I get a nullPointerException on the line that's supposed to compare the strings retrieved by getID() and the userInput string. The array is initialized as follows:

Salesperson[] staffList;
staffList = new Salesperson[20];

Here is the loop in question, the if statement is the line that throws the NPE:

for(i = 0; i < staffList.length; i++) 
 {
     if(staffList[i].getID().equals(idNum))
     {
          duplicateID = true;
     }
 }

Here is the class for the Salesperson array:

public class Salesperson
{
private String name;
private String idNum;
private double annSales;

//Various getter and setter methods here
}

If I missed anything please let me know. I've used Stack Overflow in the past but have never asked a question myself. I've tried searching around here but have yet to find anything that helped me. Thanks in advance!

  • `staffList` is an array which is the placeholder for 20 elements, so for loop passes without `NPE` because it's length is 20. When it goes to `staffList[i]` to retrieve `Salesperson` object, it throws `NPE`, there is no object. At this time, `staffList[i] = null` So, `null.getID()` throws `NPE`. – Pradip Karki Mar 09 '19 at 06:23
  • you could also define a variable to maintain the number of elements in the array (no need to loop the whole array if it is not full); sure, testing if the element is `null` before calling its methods (`staffList[i] != null && staffList[i].get...`) does not harm . Alternative: use an `ArrayList` that grows as needd... – user85421 Mar 09 '19 at 07:10

1 Answers1

1

You can update your code something like below to avoid NPE.

    Salesperson[] staffList;
        staffList = new Salesperson[20];

        for(int i = 0; i < staffList.length; i++)
        {
            Salesperson salesPerson = staffList[i]; // staffList[i] i.e salesPerson = null.... null.getId throws NPE.

System.out.println("sales =" + sales); // sales = null
            if(sales != null) {
                if (sales.getId().equals(idNum)) {
                      //Do something..
                }
            }

        }
KZapagol
  • 752
  • 3
  • 9
  • There is no need to nest if-statements here, a single if will work as well `if (sales != null && sales.getId().equals(idNum))`. – Mark Rotteveel Mar 09 '19 at 08:14
  • @MarkRotteveel Yes there is no need to nest if statements. Single if statements can also work as you mentioned. – KZapagol Mar 09 '19 at 08:26