Reputation: 644
I'm trying to draw a circle with the help of Java but I'm stuck This is what I've done so far,
public class Circle {
public static void DrawMeACircle(int posX, int posY, int radius) {
int a = 10;
int b = 10;
int x = posX - a; //x = position of x away from the center
int y = posY - b;
int xSquared = (x - a)*(x - a);
int ySquared = (y - b)*(y - b);
for (int i = 0;i <=20; i++) {
for (int j = 1;j <=20; j++) {
if (Math.abs(xSquared) + (ySquared) >= radius*radius && Math.abs(xSquared) + (ySquared) <= radius*radius) {
System.out.println("#");
} else {
System.out.println(" ");
}
}
}
}
public static void main(String[] args){
DrawMeACircle(5,5,5);
}
}
As you can see, this doesn't work out properly. Does anyone know how this can be solved? I'm thankful for any help possible, Michael.
Upvotes: 1
Views: 9050
Reputation: 11463
First of all, your inner if
condition does not depend from i
and j
, so is a constant. That means the same symbol is printed every time, a space symbol.
Next, you're using System.out.println(" ");
every time, adding a newline to each symbol. So, result looks like a column of spaces.
Last, but not least: drawing area is limited by 20x20 "pixels" and unable to fit large circles.
You can fix all these points together with something like
public class Circle {
public static void DrawMeACircle(int posX, int posY, int radius) {
for (int i = 0;i <= posX + radius; i++) {
for (int j = 1;j <=posY + radius; j++) {
int xSquared = (i - posX)*(i - posX);
int ySquared = (j - posY)*(j - posY);
if (Math.abs(xSquared + ySquared - radius * radius) < radius) {
System.out.print("#");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
public static void main(String[] args){
DrawMeACircle(5,15,5);
}
}
which gives us somewhat similar to the circle.
Upvotes: 1