【如何实现用Java打印三角形图案(代码示例)】给定数字N, 任务是打印以下模式:
例子:
Input : 10
Output :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * * Input :5
Output :
*
* *
* * *
* * * *
* * * * *
打印上述图案需要嵌套循环。外循环用于运行作为输入给出的行数。外循环中的第一个循环用于在每个星星之前打印空格。如你所见, 当我们向三角形的底部移动时, 每行的空格数减少, 因此此循环的每次迭代运行时间减少一倍。外循环中的第二个循环用于打印星星。如你所见, 随着我们向三角形的底边移动, 每行中的恒星数量都会增加, 因此此循环在每次迭代中运行的次数增加了一倍。如果此程序为空运行, 则可以实现清晰度。
// 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();
}
}
}
推荐阅读
- CSS overflow(溢出)用法示例代码介绍
- jQuery.fn.extend()方法用法示例介绍
- Linux虚拟化(Linux容器(lxc)详细指南)
- 如何使用Python读取、写入和解析JSON(完整指南)
- 解释JavaScript中for(.. in)和for(.. of)循环语句之间的区别()
- SPARK 应用如何快速应对 LOG4J 的系列安全漏洞
- Linux之date命令
- 爆测一周!22年必看最细致代码托管工具测评
- #yyds干货盘点#动力节点王鹤Springboot教程笔记SpringBoot集成Dubbo