如何使用用户指定的行数打印整数三角形?

时间:2014-08-05 16:03:41

标签: java arraylist nested-loops

我想进一步练习使用ArrayLists和Nested Loops,所以我想到了以下有趣的问题。

行数由用户专门设置,有些东西会出现如下:

Enter a number: 5
1
2      3
4      5      6
7      8      9      10
11     12     13     14     15

有人可以就这个问题给我一些建议吗?提前谢谢!

1 个答案:

答案 0 :(得分:2)

我的第一个forloop用于创建三角形行,第二个用于创建coloumns。

对于每一行,您需要先打印第一个值然后再打印空格。

空格数量应减少每行一个,而颜色数量减少一个。空间将增加一个

对于居中输出,每行增加星数2.

import java.util.Scanner;
class TriangleExample
{
    public static void main(String args[])
    {
        int rows, number = 1, counter, j;
        //To get the user's input
        Scanner input = new Scanner(System.in);
        //take the no of rows wanted in triangle
        System.out.println("Enter the number of rows for  triangle:");
        //Copying user input into an integer variable named rows
        rows = input.nextInt();
        System.out.println(" triangle");
        System.out.println("****************");
        //start a loog counting from the first row and the loop will go till the entered row no.
        for ( counter = 1 ; counter <= rows ; counter++ )
        {
            //second loop will increment the coloumn 
            for ( j = 1 ; j <= counter ; j++ )
            {
                System.out.print(number+" ");
                //Incrementing the number value
                number++;
            }
            //For new line
            System.out.println();
        }
    }
}