Printing a checkerboard or square pattern

I’m learning Java and I’m currently trying to make some ASCII art with the program. I was able to make a hollow diamond, but I’m struggling with creating a “checkerboard” or square pattern. I’m trying to create something that looks like this:

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

For some reason it keeps coming out like this:

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

I know the issue is with my for-loop. Since I just learned about nested loops, I’m still trying to understand the logic. My middle loop controls the spaces, and no matter what value I put for s (my incrementing variable), it still makes the pattern come out weird.

Here is my code:

public class ASCII_Art {
    public static void squares() {
        System.out.println("***n***   ");
    }

    public static void main(String[] args) {
        for (int i = 0; i <= 5; i++) {
            for (int y = 0; y < i - 4; y++) {
                squares();
                System.out.print("   ");
                squares();
            }
        }
    }
}

I made a square method since I read that methods make everything clearer and easier since you don’t have to rewrite the same code multiple times.

Answer

So basically the problem here is that your square method prints out three asterisks and then goes to a new line. You then can’t go back to the previous line, which is why the first square looks good, but then the others look out of place. If you look at the output, the first square is being printed. You then print the white-spaces and then another square. But this second square does not start on the first line. It starts on the second, so what ends up happening is the first three asterisks are printed, and then n tells it to go to a new line, and then the other three asterisks are printed which is why they look separated. Like other people have suggested, use t, not n.

Leave a Reply

Your email address will not be published. Required fields are marked *