Skip to content
Advertisement

Display squares of asterisks, filled and hollow, side by side

I’m currently trying to display a filled asterisk square and a hollow asterisk :

********** **********
********** *        *
********** *        *
********** *        *
********** **********

Instead, I’m getting this output:

**********
**********
**********
**********
**********
**********
*        *
*        *
*        *
**********

I’m not so sure how to make it side by side instead of up and down. Do I have to put the hollow nested loop inside the filled loop or do I have to do something else? Here is my code:

public class doubleNestedLoops {
    public static void main(String[] args) {
        //Filled Square
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 10; j++) {
                System.out.print("*");
            }
            System.out.println();
        }

        //Hollow Square
        for (int j = 1; j <= 5; j++) {
            for (int i = 1; i <= 10; i++) {
                if (j == 1 || j == 5 || i == 1 || i == 10) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
}

Advertisement

Answer

John Martinez’ answer works fine, but it’s a little inefficient. I’ll put a step by step below your code, which I revamped:

public class Main {
    public static void main(String[] args) {
        //Both Squares
        StringBuilder filledLine = new StringBuilder(10);
        StringBuilder hollowLine = new StringBuilder(10);
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 10; j++) {
                filledLine.append("*");
                if (i == 1 || i == 5 || j == 1 || j == 10) {
                    hollowLine.append("*");
                } else {
                    hollowLine.append(" ");
                }
            }
            System.out.println(filledLine + " " + hollowLine);
            filledLine.delete(0, filledLine.length());
            hollowLine.delete(0, hollowLine.length());
        }
    }
}

Step 1: Convert your two loops to one loop. This is because you cannot print on the same line once you’ve made a new line.

Step2: Because we’ll be using Strings in a loop, it’s more efficient to use a StringBuffer, so we don’t constantly make new strings

Step 3: Write all of the output from your logic to the buffers instead of the console.

Step 4: Print the buffers one line at a time, as we fill them.

Step 5: Profit!

Advertisement