java - 无法创建点平面

标签 java

我正在尝试使用以下代码创建一个点平面:

类(class)环境:

public class Environment {
public ArrayList<Point> plane = new ArrayList<Point>();


public void addToPlane(Point point) {
    plane.add(point);
}
public void showplane() {
    for(int x=1; x<=2500; x++) {
        Point point2 = new Point();
        point2 = plane.get(x);
        System.out.println("x = "+point2.getX()+"; y = "+point2.getY());
    }
}

}

类环境测试:

    public class EnvironmentTest {

    public static void main(String[] args) {
        Environment env = new Environment();
        Helper help = new Helper();

        help.createPlane(env,50,50);
        env.showplane();
    }

}

类助手:

    public class Helper {

    public void createPlane(Environment env, int i, int j) {
        Point point = new Point();
        for(int x=0; x<=i; x++) {
            for(int y=0; y<=j; y++) {   
                point.setLocation(x, y);
                System.out.println(x+"+"+y);
                env.addToPlane(point);
            }
        }
    }
}

当我运行 showplane() 时,我在控制台中得到的是

...
50+38
50+39
50+40
50+41
...

现在一切都很好,但是当我尝试列出我的观点时,我只得到:

x = 50.0; y = 50.0
x = 50.0; y = 50.0
x = 50.0; y = 50.0
x = 50.0; y = 50.0
x = 50.0; y = 50.0

我哪里出错了?

最佳答案

//Point point = new Point(); // removed
for(int x=0; x<=i; x++) {
    for(int y=0; y<=j; y++) {   
        Point point = new Point(); // added
        point.setLocation(x, y);
        System.out.println(x+"+"+y);
        env.addToPlane(point);
    }
}

您只创建一个 Point 对象(因此相同的值会一遍又一遍地显示)。您需要在循环中为每个点创建一个新的 Point 对象。

关于java - 无法创建点平面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33834045/

相关文章:

java - 是否有允许间隙的列表实现?

java - 将 Java Appp 部署到 App Engine 时出错?无法获取系统 Java 编译器。请使用 JDK,而不是 JRE?

java - 将 XPath 转换为 CSS 选择器

java - 如何解决这种拒绝服务问题的可能性?

java - 如果我只想在其中使用 Java,Eclipse 和 Netbeans 有什么区别?

java - DRY:AsyncTasks 的案例

java - 如何避免嵌套空检查

java - EJB 3.1 中 Bean 未注入(inject),只有该 Bean 具有此行为

java - 使用 .toArray() 将 ArrayList 转换为 Int [] 数组?或者...?

java - 将整数时间戳转换为java日期