Java 新手并出现错误“int 无法取消引用”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15857377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:04:29  来源:igfitidea点击:

New to Java and have the error "int cannot be dereferenced"

java

提问by Tian

I'm new to java and I've been working on this exercise for a while, but keep receiving the error: int cannot be dereferenced. I saw couple of similar questions but still cannot figure out my own case. Here is the complete codes:

我是 Java 新手,我已经在这个练习上工作了一段时间,但一直收到错误:int 不能被取消引用。我看到了几个类似的问题,但仍然无法弄清楚我自己的情况。这是完整的代码:

package inclass;

class OneInt {
  int n;

  OneInt(int n) {
    this.n = n;
  }

  @Override public boolean equals(Object that) {
    if (that instanceof OneInt) {
        OneInt thatInt = (OneInt) that;
        return n.equals(thatInt.n); // error happens here
    } else {
        return false;
    }
  }

  public static void main(String[] args) {
    Object c = new OneInt(9);
    Object c2 = new OneInt(9);
    System.out.println(c.equals(c2));
    System.out.println(c.equals("doesn't work"));
  } 
}

Thank you very much for helping me with this little trouble.

非常感谢你帮我解决了这个小麻烦。

回答by Bernhard Barker

equalsis a method of a class. intis a primitive, not a class. Simply use ==instead:

equals是一个类的方法。int是一个原始类型,而不是一个类。只需使用==

return n == thatInt.n;

回答by Code-Apprentice

To compare ints, just use the ==operator:

要比较ints,只需使用==运算符:

if (n == thatInt.n)

Note that intis not a class, so you can neveruse the .operator with an intvariable.

请注意,这int不是一个类,因此您永远不能.运算符与int变量一起使用。