Question

I did an exercise in one of my books to get this output. We are supposed to use nested loops and basic java. I could not format the output in here but the code below produces the correct output. I got it to print the correct output but I feel like it is very redundant, mainly with the loops regarding the * and spaces if you have a better method for doing this please share!

private static void printDesign(){
    int astrickStopper = 1;
    int slashStopper = 1;
    for (int lines = 1; lines <= 7; lines++) {
        for (int firstAstrick = 6; firstAstrick >= astrickStopper; firstAstrick--) {
            System.out.print("*");
        }
        for (int spaces = 1; spaces <= slashStopper; spaces++) {
            System.out.print(" ");
        }
        for (int forwardSlash = 6; forwardSlash >= slashStopper; forwardSlash--) {
            System.out.print("//");
        }
        for (int backSlash = 1; backSlash < slashStopper ; backSlash++) {
            System.out.print("\\\\");
        }
        for (int spaces = 1; spaces <= slashStopper; spaces++) {
            System.out.print(" ");
        }
        for (int secondAstrick = 6; secondAstrick >= astrickStopper; secondAstrick--) {
            System.out.print("*");
        }
        astrickStopper = astrickStopper + 1;
        slashStopper = slashStopper + 1;
        System.out.println();
    }
}
Was it helpful?

Solution

The code you wrote seems like it meets the problem description. You could move the inner loop into a function that outputs a given sequence of characters a certain number of times, then you would just be calling the function 6 times instead of having 6 inner loops.

public void printChars(int count, String chars) {
    for (int i = 0; i < count; i++) {
        System.out.print(chars);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top