“int cannot be dereferenced” in Java

2019-01-07 22:31发布

I'm fairly new to Java and I'm using BlueJ. I keep getting this "Int cannot be dereferenced" error when trying to compile and I'm not sure what the problem is. The error is specifically happening in my if statement at the bottom, where it says "equals" is an error and "int cannot be dereferenced." Hope to get some assistance as I have no idea what to do. Thank you in advance!

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();
            }
        }
    }
}

标签: java int bluej
6条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-07 22:45

Change

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

to

id == list[pos].getItemNumber()

For more details, you should learn the difference between the primitive types like int, char, and double and reference types.

查看更多
我命由我不由天
3楼-- · 2019-01-07 22:46

As your methods an int datatype, you should use "==" instead of equals()

try replacing this if (id.equals(list[pos].getItemNumber()))

with

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

it will fix the error .

查看更多
Lonely孤独者°
4楼-- · 2019-01-07 22:47

id is of primitive type int and not an Object. You cannot call methods on a primitive as you are doing here :

id.equals

Try replacing this:

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

with

        if (id == list[pos].getItemNumber()){ //Getting error on "equals"
查看更多
迷人小祖宗
5楼-- · 2019-01-07 22:48

Assuming getItemNumber() returns an int, replace

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

with

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

查看更多
孤傲高冷的网名
6楼-- · 2019-01-07 22:56

Basically, you're trying to use int as if it was an Object, which it isn't (well...it's complicated)

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

Should be...

id == list[pos].getItemNumber()
查看更多
萌系小妹纸
7楼-- · 2019-01-07 23:03

try

id == list[pos].getItemNumber()

instead of

id.equals(list[pos].getItemNumber()
查看更多
登录 后发表回答