user3120910 - 11 months ago 88

Java Question

I'm currently trying to implement a draw method for a circle however my only tools are drawing lines from multiple points (specifcally for this example, I have a "pen" that i can move to, then draw from that location to a new location on a grid.)

This is my current code

`public void draw(WinPlotter plotter){`

setPenColor(plotter);

plotter.moveTo(xo,yo); //xo,yo being original X and Y cords (origin)

for (int i = 0; i > 360; i++){

double x = Math.sin(i) * radius;

double y = Math.cos(i) * radius;

plotter.drawTo(x,y);

}

}

I'm not sure what i'm missing, but this actually won't output anything at all, I've tested to make sure that xo and yo are being passed to the method properly, so i'm confident that my problem lies in my logic of trying to draw a circle from lines.

EDIT:

`public void draw(WinPlotter plotter){`

setPenColor(plotter);

plotter.moveTo(xo,yo+radius);

for (int i = 0; i <= 360; i++){

double x = xo+ Math.sin(i * (Math.PI / 180)) * radius;

double y = yo+ Math.cos(i) * radius;

plotter.drawTo(x,y);

}

}

This is my fixed code. Still does not create circles, instead creates this (the circles are supposed to be on the top)

Answer Source

Issue 1: `sin()`

and `cos()`

are expecting inputs in radians, not degrees. To get radians, multiply `i`

by `Math.PI / 180`

.

Issue 2: The conditional in your loop is backward; you want `i < 360`

, not `i > 360`

. If you want to close the circle, use `i <= 360`

instead.

Issue 3: You're not adding `xo`

and `yo`

to the calculated x/y coordinates, so you're drawing all of the circle except the first point at the (0, 0) origin.

Issue 4: Your initial `moveTo()`

goes to the center of the circle instead of the point on the circle at 0 degrees.