案例:输出菱形的代码如下图形
上三角形的行数(rows)由用户输入
*
***
*****
*******
*********
***********
*********
*******
*****
***
*
解题思路:
找规律(下图是找出的规律):
行号 | 星号 | 空格 |
1 | 1 | Rows-1 |
2 | 3 | Rows-2 |
Rows | 2*Rows-1 | Rows-row |
Rows+1 | 2*Rows-1-2 | 1 |
Rows+2 | 2*Rows-1-2-2 | 2 |
代码:
public static void main(String[] args) {
System.out.println("请输入行/列数"); //输入数
Scanner scan = new Scanner(System.in);//
//int cols = scan.nextInt();
int rows = scan.nextInt();//接收输入
for (int row = 1; row <=2*rows-1; row++) {//控制空格数
for (int col = 1; col <= Math.abs(rows-row); col++) {
System.out.printf(" ");//输出结果
}
for (int col = 1; col <= 2*rows-1-2*Math.abs(rows-row); col++) {//输出星号
System.out.printf("*");
}
System.out.printf("\n");
}
}