java - 在java中移动非静态坐标

标签 java point coordinate

我有一个方法转换,需要构造一个 Cooperative 类的新对象,其中坐标 dx 向右移动,dy 向下移动。例如,使用表示位置 (1,1) 的 pos 调用 pos.shift(-1,1) 将产生新位置 (0,2)。 Eclipse 给我这个错误消息:

Cannot make a static reference to the non static method shift(int, int) from type Coordinate

这是我的一段代码,它应该执行此转换:

/** 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);
}

也许我太愚蠢了,但我没有好主意来解决这个问题。

这是整个代码:

 /** 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);
 }
}

大家有什么好主意吗?

最佳答案

在您的方法shift中存在几个问题

 public Coordinate shift(int dx, int dy) {
     pos = pos.shift(this.x + dx, this.y + dy);
 }
  • 该方法引用了一个变量pos,pos尚未声明并且 所以不存在。它似乎也没有任何作用,因为所有 没有它也可以完成坐标移动。
  • 方法 shift 没有 return 语句,这意味着不会返回新的坐标
  • 如果posCooperative类型的变量,那么shift将调用pos.shift将调用pos.shift将永远调用pos.shift等,直到发生StackOverflowException<

此方法的更正版本是

 public Coordinate shift(int dx, int dy) {
     return new Coordinate(this.x + dx, this.y + dy);
 }

注意如何:

  • 使用构造函数创建新的坐标
  • 这个新的坐标从方法中传递

方法 checkBoundaries(int xSize, int ySize)

此方法不会影响提到的具体问题。然而它的行为并不像你想象的那样。 0|1 是 bitwise 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;
 }

关于java - 在java中移动非静态坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20264479/

相关文章:

java - 同一文件夹中的 Scala 导入类

c# - 3d到2d点转换

r - 标准化各组的点大小

javascript - 如何从鼠标单击坐标获取 WebGL 3d 空间中的对象

java - 欧拉计划 #3 双除法

java - 为什么我们需要将 toString 方法与 stringbuilder 一起使用

java - 如何使用 sqrt(-x) 处理 NaN?

java - 基础Java - 如何使用方法等

Java MouseEvent位置不准确

objective-c - 如何在iOS中存储GPS坐标?