【发布时间】:2017-06-10 12:36:04
【问题描述】:
作为个人项目的一部分,我需要生成一个直立的方格(只有整数点的方格)。
代码如下:
private ArrayList<Point> generateSquare(int area, Point center) {
int length = (int) Math.rint(Math.sqrt(area));
Point startingPoint = new Point((int) Math.rint(center.getX() - (length / 2)), (int) Math.rint(center.getY() - (length / 2))); // get bottom left corner
ArrayList<Point> squarePoints = new ArrayList<>();
for (int i = 0; i <= length - 1; i++) { // iterate for the length of the square
squarePoints.add(new Point(startingPoint.x + i, startingPoint.y));
}
for (int i = 0; i <= length - 2; i++) { // iterate for the length of the square minus one since I already have the first row. 2 is subtracted to to account for index 0. This iterates for each row.
for (int j = 0; j <= length - 1; j++) { // iterates for the points in each row. Index 0 is needed, so length is minus one.
Point tempPoint = squarePoints.get(i); // gets the point to manipulate
squarePoints.add(new Point(tempPoint.x, startingPoint.y + j));
}
}
return squarePoints;
}
从逻辑上讲,这就是我想要做的:
- 我得到了要生成的晶格的中心点。从 这个,我能找到左下角。这存储为 起点。
- 然后我通过迭代生成正方形的底行点 正方形的长度并将新点添加到 ArrayList 称为 squarePoints。
- 然后我再次迭代平方的长度减一,因为 我已经有了第一行。
- 在这个 for 循环中,我再次迭代正方形的长度。 在这里,我得到一个 tempPoint,它是 squarePoints 中的一个点 当前迭代值的索引处的 ArrayList。这 这样做的原因是我要从 原来的行。然后我添加一个具有相同 x 的新点 坐标为 tempPoint,y 坐标为 起始点加上当前迭代。
此过程的目标是添加正方形的所有剩余行。
不过,目前,当我运行它时,它返回的点数不正确。我希望其他人可以确定我的代码存在的问题和/或提供更好的解决方案。
另外,由于这是一个控制台应用程序,在其中使用 AWT 中的 Point 类会是一种不好的做法吗?
感谢任何帮助。
谢谢。
【问题讨论】:
-
预期结果是什么?正方形区域内的所有整数点 ?还是只是周界点?