0

有一个练习希望我并排输出与输入的数字一样多的三角形。所以我的代码如下所示:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int triangles = in.nextInt();
    int i, j, k;                            
        for (int n = 1; n <= triangles; n++) {
            for (i = 1; i <= triangles; i++) {
                for (k = 1; k <= triangles - i; k++) {
                    System.out.print(" ");
                }
                for (j = k; j <= triangles; j++) {
                    System.out.print("*");
                }
                for(int l = triangles - 1; l > k - 1; l--) {
                    System.out.print("*");
                }System.out.println("");
            }
        } 

输入 5 和输出是五个三角形,每个三角形有 5 条线,但它们都相互重叠。

难道我做错了什么?

4

1 回答 1

1

这是一个丑陋的mofo(有效):

public static void main(String[] args) {
    int triangles = 5;

    //initialize column count
    int columns = triangles * 2 - 1;
    int[] starsPerRow= new int[triangles];

    //how many stars in each row
    for (int i=0; i<triangles; i++) {
        starsPerRow[i] = i*2+1;
    }

    //create a triangle "template". only one triangle map
    char[][] triangeMatrix = new char[triangles][columns];
    for (int i=0; i<triangles; i++) {
        for (int j=0; j<(columns - starsPerRow[i])/2; j++) {
            triangeMatrix[i][j] = ' ';
        }
        for (int j=0; j<starsPerRow[i]; j++) {
            triangeMatrix[i][j + (columns - starsPerRow[i])/2] = '*';               
        }
        for (int j=0; j<(columns - starsPerRow[i])/2; j++) {
            triangeMatrix[i][j + (columns + starsPerRow[i])/2] = ' ';               
        }
    }

    //print triangle map n times
    for (int i=0; i<triangles; i++) {
        for (int j=0; j<triangles; j++) {
            for (int k=0; k<columns; k++) {
                System.out.print(triangeMatrix[i][k]);
            }
        }
        System.out.println();
    }

}
于 2013-06-16T03:40:48.227 回答