How to print a triangle of integers with number of lines specified by the user? [closed]

淺唱寂寞╮ 提交于 2019-12-11 18:22:51

问题


I would like to further exercise myself on the use of ArrayLists and Nested Loops, so I thought of the following interesting problem.

The number of lines is specialized by the user and something would come out like this:

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

Can anybody give me some advice for doing this question? Thanks in advance!


回答1:


My first forloop is for creating rows of triangle and second is for creating coloumns.

For each row, you need to print first value and then spaces.

The number of spaces should decrease by one per row and in coloumns no. of space will increase by one per coloumn

For the centered output, increase the number of stars by two for each row.

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


来源:https://stackoverflow.com/questions/25143410/how-to-print-a-triangle-of-integers-with-number-of-lines-specified-by-the-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!