如何检查未设置的对象是否具有属性

时间:2019-03-23 14:43:02

标签: java class attributes

我正在尝试形成一种方法来调用对象以检查其是否包含类中的某些属性

这是我到目前为止尝试过的代码

public class BoundingBox {

    public int x, y, width, height;

    public BoundingBox() {

    }

    public Integer getX() {
        return x;
    }

    public void setX(Integer x) {
        this.x = x;
    }

    public Integer getY() {
        return y;
    }

    public void setY(Integer Y) {
        this.y = y;
    }

    public boolean contains(int x, int y) {
        if (x == getX() & y == getY()) {
            return true;
        } else {
            return false;
        }
    }
}

但是,当我创建具有所有属性值保持为10的对象并使用object.contains(15,15)对其进行测试时,它不会返回false

4 个答案:

答案 0 :(得分:2)

在Java中,运算符&可以具有不同的含义:

  
      
  • &按位运算符
  •   
  • &&逻辑运算符
  •   

在if语句if (x == getX() & y == getY()) {中,您使用了& 按位运算符,而不是&& 逻辑运算符
另外,setY方法中有一个错字,如@alvinalvord所述,将intInteger进行比较会产生意想不到的结果。

像这样更改您的代码,它将起作用:

public class BoundingBox {

    public int x, y, width, height;

    public BoundingBox() {

    }

    public Integer getX() {
        return x;
    }

    public void setX(Integer x) {
        this.x = x;
    }

    public Integer getY() {
        return y;
    }

    public void setY(Integer y) {
        this.y = y;
    }

    public boolean contains(int x, int y) {
        return getX().equals(x) && getY().equals(y);
    }
}

备用代码

或者,如果没有特别的理由保留Integer变量,则可以这样更改代码:

public class BoundingBox {

    public int x, y, width, height;

    public BoundingBox(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public boolean contains(int x, int y) {
        return getX() == x && getY() == y;
    }
}

答案 1 :(得分:1)

比较int和Integer也有一些问题see here。最好的int为您的吸气剂。

答案 2 :(得分:-1)

您在contains中的测试缺少与号,应为&&而不是&。单个&符是按位与,而不是逻辑与。

答案 3 :(得分:-1)

您的setY方法存在错误:

 public void setY(Integer Y) {
        this.y = y;
 }

Y是大写字母,这就是this.y = y不起作用的原因。这行代码没有意义,这就是为什么在contains()方法中比较y时会得到错误的原因。 更改为:

 public void setY(Integer y) {
            this.y = y;
 }