【问题标题】:How to print a triangle of integers with number of lines specified by the user? [closed]如何打印具有用户指定行数的整数三角形? [关闭]
【发布时间】:2014-08-05 16:03:41
【问题描述】:

我想进一步锻炼自己对ArrayLists和Nested Loops的使用,所以我想到了以下有趣的问题。

行数由用户指定,结果如下:

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

有人可以给我一些关于做这个问题的建议吗?提前致谢!

【问题讨论】:

  • 最好的学习方式是通过实践。尝试一些东西,然后在这里发布您的问题。 :)

标签: java arraylist nested-loops


【解决方案1】:

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

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

每行和列中的空格数应减少一个。每列的空间将增加一个

对于居中的输出,每行增加两颗星。

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

【讨论】:

  • 清晰准确!但是变量“number”与for循环中的变量“i”和“j”没有关系。为什么会起作用?
  • number 变量初始化为 1,然后每次解析都会增加 1,因此它不会在三角形中打印 1,2,3...10
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-09
  • 2014-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-03
  • 1970-01-01
相关资源
最近更新 更多