1.打印菱形
任务:打印一个上下对称的菱形
*
***
*****
*******
*********
***********
*********
*******
*****
*
1首先做一个直角三角形
int rows = 6;
for(int i=1;i<=rows;i++){//i=1
for(int j = 1; j <= i*2-1; j++){//只能干预的位置是j的范围
System.out.print("*");
}
System.out.println();
}
*
***
*****
*******
*********
***********
2.做一个空白位置
int rows = 6;
for(int i=1;i<=rows-1;i++){ //i=2
for(int j=rows-1;j>i;j--){//j=5
System.out.print("&");
}
System.out.println();
}
&&&&&
&&&&
&&&
&&
&
在将两者融合做一个等腰三角形
int rows = 6;
for(int i = 1;i <= rows;i++){ //i=2
for(int j = rows - 1;j > i;j--){//j=5
System.out.print("&");
}
for(int k = 1; k <= i*2-1; k++){//只能干预的位置是j的范围
System.out.print("*");
}
System.out.println();
}
&&&&&*
&&&&***
&&&*****
&&*******
&*********
***********
再做一个完整的菱形
int rows = 6;
for(int i = 1;i <= rows;i++){ //i=2
for(int j = rows;j > i;j--){//j=5
System.out.print(" ");
}
for(int k = 1; k <= i*2-1; k++){
System.out.print("*");
}
System.out.println();
}
for(int i=rows-1;i>0;i--){//i=1 23456
for(int j = 1; j <=rows-i ; j++){
System.out.print(" ");
}
for(int k = 1; k <= 2*i-1;k++){
System.out.print("*");
}
System.out.println();
}
*
***
*****
*******
*********
***********
*********
*******
*****
***
*
再加入可用控制台选择菱形的高度
import java.util.Scanner;
class sumer{
public static void main (String[] args){
Scanner input = new Scanner(System.in);
int totalRows=0; //总行数
do{System.out.println("请输入总行数:");
totalRows =input.nextInt();
}while(totalRows %2 ==0);//判断行数为奇数否则重新输入
int halfrows = totalRows/2+1;//上半行
int downfrows = totalRows/2;//下半行
for(int i = 1;i <=halfrows;i++){ //上
for(int j = halfrows;j>i;j--){//上空白处
System.out.print(" ");
}
for(int k = 1; k <= i*2-1; k++){//上图形处
System.out.print("*");
}
System.out.println();
}
for(int i=downfrows;i>0;i--){//下
for(int j = 1; j <=downfrows-i+1 ; j++){//下空白处
System.out.print(" ");
}
for(int k = 1; k <= 2*i-1;k++){//下图形处
System.out.print("*");
}
System.out.println();
}
}
}