I have to print a circle (taking as input it's radius, the coordinates of the center of the circle (cx
and cy
), and the character with which it has to be drawn).
I wrote a series of if-blocks for the axes and the circle. They work well if I use them separately, but when I put them in the same method (I have to have only one method) they overlap in an undesirable way.
Note: in case if the character overlaps the axes, the character has priority.
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()
}
}
Here is the onCircle
method. It verifies for every i,j
if it is on the outline of the circle to be drawn.
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;
}
Here is my output (without the last print statement):
^ |
*** |
* * |
* * |
* * + - - - - -*-*-*- >
Here is my output (with the last print statement):
^
|
***
|
* *
|
* *
|
* *
+ - - - - -*-*-*- >
Here is what I should get: