【问题标题】:"int cannot be dereferenced" in JavaJava中的“int不能被取消引用”
【发布时间】:2013-10-07 04:42:56
【问题描述】:

我对 Java 还很陌生,我正在使用 BlueJ。我在尝试编译时不断收到这个“Int cannot be dereferenced”错误,我不确定问题是什么。该错误特别发生在我底部的 if 语句中,它说“等于”是一个错误,“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();
            }
        }
    }
}

【问题讨论】:

  • 您正在尝试使用int,其中应该使用IntegerNumberObject...int 没有任何方法

标签: java int bluej


【解决方案1】:

id 是基本类型 int 而不是 Object。您不能像在此处那样调用原语上的方法:

id.equals

尝试替换这个:

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

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

【讨论】:

  • 如果需要使用Integer.compareTo怎么办?
【解决方案2】:

基本上,您尝试使用int,就好像它是Object,但事实并非如此(嗯...这很复杂)

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

应该是……

id == list[pos].getItemNumber()

【讨论】:

  • 一个疑问:== 比较对象的引用和比较基元的值,对吧?如果我错了,请纠正。
  • 是的。基元是特殊的。
  • 实际学习界面时我收到了这个错误,谷歌搜索把我带到了这个答案。可以的话请看:error:int cannot be dereferencedSystem.out.println("A = " + A.AB);调用SOP的类实现了一个interface C,A是C的超接口。两个接口都定义了int AB。 A.AB 发生错误。
  • int AB 不能在任何interface 中声明,它只能在class 中声明...
【解决方案3】:

假设getItemNumber()返回int,替换

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

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

【讨论】:

    【解决方案4】:

    改变

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

    id == list[pos].getItemNumber()
    

    有关详细信息,您应该了解基本类型(如 intchardouble)与引用类型之间的区别。

    【讨论】:

      【解决方案5】:

      由于您的方法是 int 数据类型,您应该使用“==”而不是 equals()

      尝试替换这个 if (id.equals(list[pos].getItemNumber()))

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

      它将修复错误。

      【讨论】:

        【解决方案6】:

        试试

        id == list[pos].getItemNumber()
        

        而不是

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-03-26
          • 2020-06-08
          • 1970-01-01
          • 2015-05-21
          • 2023-03-31
          相关资源
          最近更新 更多