我正在尝试使用以下代码创建一个点平面:
类(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/