Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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, wich 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading