gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:05:22 25 4
gpt4 key购买 nike

我试图形成一个方法来调用一个对象来检查它是否包含类中的一些属性

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

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

最佳答案

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

  • & : Bitwise operator
  • && : Logical operator

在 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;
}
}

关于java - 如何检查未设置的对象是否具有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55314889/

25 4 0
文章推荐: java - 是否可以避免 IntelliJ IDEA 中的自动换行?
文章推荐: javascript - 如何使背景图片的
文章推荐: java - 旋转矩阵 90 度
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com