I'm trying to form a method to call on a object to check if it contains some of the attributes in the class
This is the code that I've tried so far
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;
}
}
}
However when I created the object with all attributes holding the value of 10 and tested it using object.contains(15,15), it does not return false
In Java the operator &
can assume different meanings:
&
: Bitwise operator&&
: Logical operator
In the if statement if (x == getX() & y == getY()) {
you used the &
bitwise operator instead of the &&
logical operator.
Plus there was a typo in the setY
method and, as stated by @alvinalvord, comparing int
with Integer
can give unexpected results.
Change your code like this and it will work:
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);
}
}
Alternative Code
Or, if there's no particular reason to keep the Integer
variables, you can change the code like this:
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;
}
}