我必须打印一个圆(将其半径、圆心的坐标作为输入(cx
and cy
),以及绘制它所用的字符)。
我为轴和圆编写了一系列 if 块。如果我单独使用它们,它们会很好地工作,但是当我将它们放在同一个方法中时(我必须只有一种方法),它们会以不期望的方式重叠。
注意:如果字符与轴重叠,则该字符优先。
public static void drawCircle(int radius, int cx, int cy, char symbol) {
// this method verifies that there are no negative
// values involved (throws error/exception)
verifyInput(radius, cx, cy);
// set the values for extension of the axes
// (aka how long are they)
int xMax = cx + radius + 1;
int yMax = cy + radius + 1;
for (int j = yMax; j >= 0; j--) {
for (int i = 0; i <= xMax; i++) {
// set of if-block to print the axes
if (i == 0 && j == 0) {
System.out.print('+');
} else if (i == 0) {
if (j == yMax) {
System.out.print('^');
}
if (j != yMax) {
System.out.println('|');
}
} else if (j == 0) {
if (i == xMax) {
System.out.println('>');
}
if (i != xMax) {
System.out.print('-');
}
}
// if block to print the circle
if (onCircle(radius, cx, cy, i, j) == true) {
System.out.print('*');
} else {
System.out.print(' ');
}
}
// I'm not sure if I need to use the print here V
// System.out.println()
}
}
这里是onCircle
方法。它验证每个i,j
如果它位于要绘制的圆的轮廓上。
public static boolean onCircle(int radius, int cx, int cy, int x, int y) {
boolean isDrawn = false;
if (Math.pow(radius,2)<=(Math.pow((x-cx),2)+Math.pow((y-cy),2))
&& (Math.pow((x-cx),2)+Math.pow((y-cy),2))<=(Math.pow(radius,2)+1)) {
isDrawn = true;
}
return isDrawn;
}
这是我的输出(没有最后一个打印语句):
^ |
*** |
* * |
* * |
* * + - - - - -*-*-*- >
这是我的输出(带有最后一个打印语句):
^
|
***
|
* *
|
* *
|
* *
+ - - - - -*-*-*- >
这是我应该得到的: