0

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();
    }
}
4

1 回答 1

0

您编写的代码似乎符合问题描述。您可以将内部循环移动到一个函数中,该函数将给定的字符序列输出一定次数,然后您只需调用该函数 6 次,而不是有 6 个内部循环。

public void printChars(int count, String chars) {
    for (int i = 0; i < count; i++) {
        System.out.print(chars);
    }
}
于 2013-09-20T04:40:06.213 回答