Reputation: 93
I have a method shift that needs to construct a new object of class Coordinate
with coordinates shifted dx
to the right and dy
down. For example, calling pos.shift(-1,1)
with pos
representing the position (1,1) would result in a new position (0,2). Eclipse gives me this error message:
Cannot make a static reference to the non static method
shift(int, int)
from typeCoordinate
This is my piece of code, which should do this shifting:
/** move the position by dx to the right and by dy down */
public Coordinate shift(int dx, int dy) {
pos = pos.shift(this.x + dx, this.y + dy);
}
Maybe I am just way too stupid but I have no good idea to solve this.
This is the whole code:
/** represents a position on a board */
public class Coordinate {
/** variables specifying horizontal position on the board */
private int x;
/** variable specifying vertical positoin on the board */
private int y;
/** constructor creating a Coordinate from x and y values */
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
/** getter for the x value */
public int getX() {
return this.x;
}
/** getter for the y value */
public int getY() {
return this.y;
}
/** check whether this position is valid for the given (quadratic) board size */
public boolean checkBoundaries(int xSize, int ySize) {
boolean check;
if (xSize == (0|1|2) && ySize == (0|1|2)) {
check = true;
} else {
check = false;
}
return check;
}
/** move the position by dx to the right and by dy down */
public Coordinate shift(int dx, int dy) {
pos = pos.shift(this.x + dx, this.y + dy);
}
}
Anyone with a good idea?
Upvotes: 2
Views: 973
Reputation: 17226
Within your method shift
there are several problems
public Coordinate shift(int dx, int dy) {
pos = pos.shift(this.x + dx, this.y + dy);
}
shift
has no return statement, meaning that no new Coordinate
is returnedpos
was a variable of type Coordinate
then shift would call pos.shift would call pos.shift would call pos.shift etc forever until a StackOverflowException occuredA corrected version of this method is
public Coordinate shift(int dx, int dy) {
return new Coordinate(this.x + dx, this.y + dy);
}
Note how:
Coordinate
is created using the constructorCoordinate
is passed out of the methodMethod checkBoundaries(int xSize, int ySize)
This method does not impact the specific problem mentioned. It doesn't however behave how you think. 0|1 is a bitwise operator, it does not give multiple options for a condition. What you wanted was several conditions seperated by the logical operator ||
public boolean checkBoundaries(int xSize, int ySize) {
boolean check;
if ((xSize==0 || xSize ==1 || xSize ==2) && (ySize==0 || ySize ==1 || ySize ==2)) {
check = true;
} else {
check = false;
}
return check;
}
Upvotes: 2