在java中创建一个颠倒的三角形

时间:2012-10-25 13:07:54

标签: java geometry

我正在努力制作我所面对的三角形。 多次尝试,但我不知道该怎么做。

我所知道的代码是:

public static void drawPyramide(int lines, char symbol, boolean startDown) {
    //TRIANGLE

    if(startDown) {
                //The triangle up side down should be here. 
            }

    else {
        int c = 1;
        for (int i = 0; i < lines; i++) {
            for (int j = i; j < lines; j++) {
                System.out.print(" ");
            }
            for (int k = 1; k <= c; k++) {
                if (k%2==0) System.out.print(" ");

                else System.out.print(symbol);
            }

        System.out.print("\n");
        c += 2;
        }
    }

}

有什么建议我可以“翻转”这个三角形吗?感谢。

3 个答案:

答案 0 :(得分:1)

要翻转三角形,您只需要改变迭代方向。您需要从i = 0转到i < lines

而不是从i = lines-1转到i >= 0

您还需要将c更改为您想要开头的空格和符号数。

看起来像这样:

int c = 2*lines;
for (int i = lines-1; i>=0; i--)
{
    for (int j = i; j < lines; j++)
    {
        System.out.print(" ");
    }
    for (int k = 1; k <= c; k++)
    {
        if (k % 2 == 0)
        {
            System.out.print(" ");
        }
        else
        {
            System.out.print(symbol);
        }
    }

    System.out.print("\n");
    c -= 2;
}

答案 1 :(得分:0)

反转第一个循环条件,即从行数开始减少它。同时相应地调整c并使其从高到低减小,例如下面:

    int c = 2*lines-1;
    for (int i = lines; i > 0; i--) {
        for (int j = i; j < lines; j++) {
            System.out.print(" ");
        }
        for (int k = 1; k <= c; k++) {
            if (k%2==0) System.out.print(" ");

            else System.out.print(symbol);
        }

      System.out.print("\n");
      c -= 2;
    }

答案 2 :(得分:0)

import java.util.Scanner;

public class EquilateralTraingle {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int side = sc.nextInt();
        constructEquTri(side);

    }

    private static void constructEquTri(int length) {
        // loop for each line
        for (int i = length; i > 0; i--) {
            // loop for initial spaces in each line
            for (int k = 0; k < length - i; k++) {
                System.out.print(" ");
            }
            // loop for printing * in each line
            for (int j = 0; j < i; j++) {

                System.out.print("*");
                System.out.print(" ");

            }
            System.out.println();
        }
    }

}
/*Output:
    10
    * * * * * * * * * * 
     * * * * * * * * * 
      * * * * * * * * 
       * * * * * * * 
        * * * * * * 
         * * * * * 
          * * * * 
           * * * 
            * * 
             * 
*/