在java中搜索值

时间:2014-07-13 23:30:36

标签: java arrays object arrayobject

我这里有一个小问题..

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 !!!");}

这是我用他的id搜索员工的代码..我跑的时收到错误信息!  这些值是由用户输入的,我没有问题

错误消息:

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

错误是指第一个if语句

1 个答案:

答案 0 :(得分:2)

如果错误引用了第一个if语句,

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

这会给你一个NullPointerException然后employee[i]必须为null。你可以检查一下,

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

或者,如果您需要一堆if测试,请使用continue ...

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