带方法调用的空指针异常

时间:2013-10-31 02:10:13

标签: arraylist nullpointerexception

好的,这是我的switch语句的一部分的代码:

 case 1: {
               System.out.print("Member ID: ");
               int key = in.nextInt();
               while(members.findItemByKey(key) == -1){
                   System.out.print("That is an invalid member ID!\nEnter a new one: ");
                   key = in.nextInt();
               }


               System.out.print("ISBN: ");

               int book = in.nextInt();
             while(books.findItemByKey(book) == -1){
                 System.out.println("That book is not in the system.\nPlease make a new choice: ");
                 book = in.nextInt();
             }
             while(stock.findItemByKey(book) != -1){  
               try {
                m = members.get(members.findItemByKey(key));
                t = books.get(books.findItemByKey(book));
            } catch (Exception e) {
                e.printStackTrace();
            }

               if(m.checkOut(t) == true){
                   stock.removeItem(t);
               }
             }

           }

以下是调用方法:

public int findItemByKey(int key){

    for(E e: list)
    {
        if(e.getKey() == key){
            return findItem(e);
        }
    }


    return -1;
}

        public int findItem(E item){

    if (item == null){
        for (int i = 0; i < numElements; i++)
            if(list[i]==null)
                return i;
    }else {
        for( int i = 0; i < numElements; i++)
            if (item.equals(list[i]))
                return i;

    }

    return -1;
}

好的,我知道这里有很多东西要看,但这就是发生的事情。当我输入无效的成员ID时,它会正常运行并不断询问用户新的成员ID,直到输入有效成员ID为止。现在,当我输入一本书时,无论我是否输入有效或无效的书,我都会得到这一行抛出的空指针异常:

if(e.getKey() == key)
书籍,会员和股票都是在我的代码中以相同的方式定义的arraylists。我不明白为什么我有这个例外与书籍而不是成员。 book和member的类定义方式相同,两者都有相同的getKey方法。

也许这个问题太多了,任何人都无法真正看到正在发生的事情。基本上我只是无法理解为什么我得到一个空指针异常而不是另一个。

编辑:决定我应该为每个类发布getKey()方法。

 public int getKey()
  {
        return ISBN;
  }

是书籍

  public int getKey()
  {
        return memberId;
  }

是成员吗。

ISBN是书籍的标识符,memberId是我的成员的标识符。一切看起来都像是在调用相同的东西,但它对于书籍而不是成员来说都是错误的。只是不明白。

1 个答案:

答案 0 :(得分:0)

e为空或从语句e.getKey()返回的值为空。

您必须确保该列表不包含null元素,然后他们的key也应该不为空。

如果你想忽略这些值为null,你可以这样做:

if(e!=null && e.getKey()!=null && e.getKey() == key){
     //statements here.
}
相关问题