2013-10-01 28 views
15

我对Java相当陌生,而且我正在使用BlueJ。在尝试编译时,我一直得到这个“Int不能被解除引用”的错误,我不确定问题是什么。该错误具体发生在我的if语句底部,它表示“equals”是一个错误,“int不能被解除引用”。希望得到一些帮助,因为我不知道该怎么做。先谢谢你!Java中的“int无法解除引用”

public class Catalog { 
    private Item[] list; 
    private int size; 

    // Construct an empty catalog with the specified capacity. 
    public Catalog(int max) { 
     list = new Item[max]; 
     size = 0; 
    } 

    // Insert a new item into the catalog. 
    // Throw a CatalogFull exception if the catalog is full. 
    public void insert(Item obj) throws CatalogFull { 
     if (list.length == size) { 
      throw new CatalogFull(); 
     } 
     list[size] = obj; 
     ++size; 
    } 

    // Search the catalog for the item whose item number 
    // is the parameter id. Return the matching object 
    // if the search succeeds. Throw an ItemNotFound 
    // exception if the search fails. 
    public Item find(int id) throws ItemNotFound { 
     for (int pos = 0; pos < size; ++pos){ 
      if (id.equals(list[pos].getItemNumber())){ //Getting error on "equals" 
       return list[pos]; 
      } 
      else { 
       throw new ItemNotFound(); 
      } 
     } 
    } 
} 
+3

你试图使用'int'其中一个'Integer','Number'或'Object'预计...'INT '没有任何方法 – MadProgrammer

回答

14

id是原始类型int而不是Object的。你不能调用一个原始的方法,你在这里做:

id.equals 

尝试更换此:

 if (id.equals(list[pos].getItemNumber())){ //Getting error on "equals" 

 if (id == list[pos].getItemNumber()){ //Getting error on "equals" 
0

假设getItemNumber()返回int,更换

if (id.equals(list[pos].getItemNumber()))

if (id == list[pos].getItemNumber())

2

基本上,你要使用int,如果它是一个Object,它不是(嗯...这是复杂的)

id.equals(list[pos].getItemNumber()) 

应该是...

id == list[pos].getItemNumber() 
+0

有一个疑问:==比较对象的引用并比较基元的值,对吗?如果我错了,请纠正。 –

+0

是的。基元是特殊的。 – MadProgrammer

+0

其实学习界面我收到这个错误和谷歌搜索带我到这个答案。麻烦看,如果你可以: '错误:整数不能dereferenced' '的System.out.println( “A =” + A.AB);' 其中SOP被称为类实现一个'接口C'并且A是C. int AB的超级接口在两个接口中都被定义。 'A.AB'发生错误。 –

0

更改

id.equals(list[pos].getItemNumber()) 

id == list[pos].getItemNumber() 

有关详细信息,你应该学会基本数据类型之间的区别就像intchardouble和引用类型。

-1

尝试

id == list[pos].getItemNumber() 

,而不是

id.equals(list[pos].getItemNumber()