Search code examples
javaarraysobjectarrayobject

searching for a value in java


i have a small problem here..

for(int i=0; i<employee.length-1;i++){

            if(employee[i].getID()==ID){
                System.out.println("Employee Record for "+employee[i].getfName()+" "+employee[i].getlName()+" (ID#"+employee[i].getID()+"):\n"
                        + "Basic Pay: "+employee[i].getSalary(0)+"\n"
                        + "Housing Allowence: "+employee[i].getSalary(1)+"\n"
                        + "Travel Allowence:  "+employee[i].getSalary(2)+"\n"
                        + "Net Salary : "+employee[i].getNetSalary()+"\n"
                        + "Taxable : "+employee[i].getTaxable());break;}


       if(i==employee.length-1){
           System.out.println("EMPLOYEE NOT FOUND !!!");}

this is my code to search for an employee by his id .. i get an error message when i run! the values are entered by the user and i don't have a problem with that

the error message :

Exception in thread "main" java.lang.NullPointerException
    at dd1318398p2.EmpRecord.searchEmpID(EmpRecord.java:103)
    at dd1318398p2.EmpRecord.main(EmpRecord.java:37)
Java Result: 1

the error is referring to the first if statement


Solution

  • If the error refers to the first if statement,

    if(employee[i].getID()==ID)
    

    And that gives you a NullPointerException then employee[i] must be null. You can check for that like,

    if (employee[i] != null && employee[i].getID()==ID)
    

    Or, if you need a bunch of if tests use a continue...

    if (employee[i] == null) continue;
    if(employee[i].getID()==ID) {
    }