Getting extra spaces in the end of a program that outputs a circle

Viewed 37

I was coding a program to display a circle in my terminal, and it works, but at the same time it doesn't because, as it outputs the circle it also outputs some extra lines in the end, which is using a lot of my screen, making hard to see the circle sometimes. Here is the code:

public static void main(String[] args){
    Draw(10);
}

private static void Draw(double r){ // r stands for radius
    for (double y = -r; y <= 2 * r; y++) {
        for (double x = -r; x <= 2 * r; x++) {
            if (isInCircle(x, y, r)) {
                System.out.print("+\s");
            } else {
                System.out.print(" \s");
            }
        }
        System.out.print("\n");
    }
}

static boolean isInCircle(double x, double y, double r) {
    return (Math.pow(x, 2)+Math.pow(y, 2)) <= r*r;
}

And this is my output:

enter image description here

As you can see, it outputs extra lines making hard to see when the terminal window is smaller.

1 Answers

Use r as the upper bound for both loops, not 2 * r.

Related