java打印方格_使用Java生成直立方格

作爲個人項目的一部分,我需要生成一個直立的正方形網格(只有整數點的平方)。使用Java生成直立方格

下面是代碼:

private ArrayList 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 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;

}

從邏輯上講,這就是我想要做的事:

我給生成格子的中心點。從 這個,我能夠找到左下角。這存儲爲起始點 。

然後,我通過迭代 來獲得正方形的最低點行數,並將新點添加到名爲squarePoints的ArrayList 。因此 我已經有第一行了。

在這個for循環中,我再次迭代正方形的長度。 在這裏,我得到一個tempPoint,它是當前迭代值索引處squarePoints ArrayList中的一個點。 這樣做的原因是,我操縱原始行 中的點。然後添加一個新座標點,其座標與tempPoint具有相同的座標,y座標爲 startingPoint加上當前的迭代。

該過程的目標是添加廣場的所有其餘行。

當然,當我運行它時,它會返回不正確的點數。我希望別人能夠用我的代碼來確定問題和/或提供更好的解決方案。

此外,由於這是一個控制檯應用程序,使用AWT中的Point類是不好的做法嗎?

任何幫助表示讚賞。

謝謝。

+0

預期結果是什麼?廣場區域內的所有整數點?或僅僅是周邊點? –

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值