作为个人项目的一部分,我需要生成一个直立的正方形点阵(只有整数点的正方形)。
以下是代码:
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;
}
从逻辑上讲,这就是我要做的事情:
此过程的目标是添加方块的所有剩余行。
目前,当我运行它时,它返回的点数不正确。我希望其他人可以通过我的代码确定问题和/或提供更好的解决方案。
另外,由于这是一个控制台应用程序,使用AWT中的Point类是不好的做法?
感谢任何帮助。
感谢。
答案 0 :(得分:0)
以下代码不会提供解决方案,但建议您找出问题的方法:
private ArrayList<Point> generateSquare(int area, Point center) {
ArrayList<Point> squarePoints = new ArrayList<>();
int length = (int) Math.sqrt(area);
System.out.println("length = "+length);
Point startingPoint = new Point((int) Math.rint(center.getX() - (length / 2)), (int) Math.rint(center.getY() - (length / 2))); // get bottom left corner
System.out.println("startingPoint = "+startingPoint); //is this bottom left ?
for (int i = 0; i <= (length - 1); i++) { // iterate for the length of the square
Point point = new Point(startingPoint.x + i, startingPoint.y);
System.out.println("First loop added "+ point); //does it add what expected ?
squarePoints.add(point);
}
//.....removed
return squarePoints;
}
更简单的方法可以是:计算最小和最大X,Y值和迭代:
for (int x = minX; x <= maxX; x++) {
for (int y = minY; y <= maxY; y++) {
squarePoints.add(new Point(x,y));
}
}