首页 课程 师资 教程 报名

用Java打印三角形图案

  • 2022-06-16 10:45:05
  • 1421次 动力节点

如何用Java打印三角形图案?动力节点小编告诉你。给定一个数字 N,任务是打印以下模式:

例子:

输入:10
输出 :                    
          *
         * *
        * * *
       * * * *
      * * * * *
     * * * * * *
    * * * * * * *
   * * * * * * * *
  * * * * * * * * *
 * * * * * * * * * *
输入:5
输出 :
     *
    * *
   * * *
  * * * *
 * * * * *

打印上述模式需要一个嵌套循环。外部循环用于运行作为输入给出的行数。外循环中的第一个循环用于打印每个星之前的空格。正如你所看到的,当我们向三角形的底部移动时,每一行的空格数都会减少,所以这个循环在每次迭代中运行的时间减少了一次。外循环中的第二个循环用于打印星星。正如你所看到的,随着我们向三角形底部移动,每行中的星数增加,所以这个循环在每次迭代中多运行一次。如果该程序是空运行的,则可以实现清晰度。

// Java Program to print the given pattern
import java.util.*; // package to use Scanner class
class pattern {
	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the number of rows to be printed");
		int rows = sc.nextInt();
		// loop to iterate for the given number of rows
		for (int i = 1; i <= rows; i++) {
			// loop to print the number of spaces before the star
			for (int j = rows; j >= i; j--) {
				System.out.print(" ");
			}
			// loop to print the number of stars in each row
			for (int j = 1; j <= i; j++) {
				System.out.print("* ");
			}
			// for new line after printing each row
			System.out.println();
		}
	}
}

 

选你想看

你适合学Java吗?4大专业测评方法

代码逻辑 吸收能力 技术学习能力 综合素质

先测评确定适合在学习

在线申请免费测试名额
价值1998元实验班免费学
姓名
手机
提交