打印三角形
一、固定行数——5行
- 思路:将整个三角形分成三部分,图中已分别用1、2、3标明。代码中要使用3个for循环,第一个for循环打印内容以“空格”形式展示,即左边的直角三角形区域,第二个for循环和第三个for循环的打印内容以“*”展示,其中第二个for循环打印出的是中间的直角三角形,第三个for循环打印出的是右边的小直角三角形。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/aac98f69b283bb6b5f18d83300800bb3.png)
package com.jacyzhu.struct;
public class TestDemo {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 5; j >= i; j--){
System.out.print(" ");
}
for (int j = 1; j <= i; j++){
System.out.print("*");
}
for (int j = 1; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
运行结果:
*
***
*****
*******
*********
二、键盘输入行数
package com.jacyzhu.struct;
import java.util.Scanner;
public class TestDemo02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入要打印的行数:");
int n = scanner.nextInt();
for (int i = 1; i <= n; i++) {
for (int j = n; j >= i; j--){
System.out.print(" ");
}
for (int j = 1; j <= i; j++){
System.out.print("*");
}
for (int j = 1; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
运行结果1:
请输入要打印的行数:
8
*
***
*****
*******
*********
***********
*************
***************
运行结果2:
请输入要打印的行数:
9
*
***
*****
*******
*********
***********
*************
***************
*****************