Printing *s as triangles in Java?

后端 未结 21 1881
囚心锁ツ
囚心锁ツ 2020-11-30 11:41

My assignment in my Java course is to make 3 triangles. One left aligned, one right aligned, and one centered. I have to make a menu for what type of triangle and then input

21条回答
  •  Happy的楠姐
    2020-11-30 12:41

    I know this is pretty late but I want to share my solution.

    public static void main(String[] args) {
        String whatToPrint = "aword";
        int strLen = whatToPrint.length(); //var used for auto adjusting the padding
        int floors = 8;
        for (int f = 1, h = strLen * floors; f < floors * 2; f += 2, h -= strLen) {
            for (int k = 1; k < h; k++) {
                    System.out.print(" ");//padding
                }
            for (int g = 0; g < f; g++) {
                System.out.print(whatToPrint);
            }
            System.out.println();
        }
    }
    

    The spaces on the left of the triangle will automatically adjust itself depending on what character or what word you want to print.

    if whatToPrint = "x" and floors = 3 it will print

    x xxx xxxxx If there's no automatic adjustment of the spaces, it will look like this (whatToPrint = "xxx" same floor count)

    xxx xxxxxxxxx xxxxxxxxxxxxxxx

    So I made add a simple code so that it will not happen.

    For left half triangle, just change strLen * floors to strLen * (floors * 2) and the f +=2 to f++.

    For right half triangle, just remove this loop for (int k = 1; k < h; k++) or change h to 0, if you choose to remove it, don't delete the System.out.print(" ");.

提交回复
热议问题