JAVA (for loop): solid diamond and hollow diamond

JAVA (for loop): solid diamond and hollow diamond

The first time I wrote a blog, I was a noob. Due to bad math, it took a long time to write these two figures. I hope it will be helpful to people who have troubles like me.
The basis of these two rhombuses is actually a rectangle.

System.out.println("==================矩形================");
		int n, m;
		for( n=1; n<6; n++) {
    
    
			for( m=1; m<6; m++) {
    
    
				System.out.print("*");
			}
			System.out.println();
		}

This is a 5 x 5 rectangle, it is very simple to write. The first for loop represents the number of rows, and the second for loop represents the number of "*" in each row. The same is true for diamonds.
Let's talk about solid diamonds first.
Solid diamond
If you can't think of a clear picture in your mind, just pick up a pen and write it. It is clear that this rhombus is composed of two parts, 1, 3, and 5 on the top and 3 and 1 on the bottom. And if you fill in the top diamonds, this will be the rectangle just written. Therefore, the space in the left half of the diamond is divided into
two parts, 2, 1, and 1, 2. You can write the code by finding the rules based on the numbers.

System.out.println("================实心菱形==============");
		int i, j;
		for( i=1; i<4; i++) {
    
                //上半部分整体的行数
			for( j=1; j<4-i; j++) {
    
          //每一行先打印空格
				System.out.print(" ");
			}
			for( j=1; j<=2*i-1; j++) {
    
       //再打印 * 。 i=1,2,3  j=1,3,5  可得规律j=2*i-1
				System.out.print("*");
			}
			System.out.println();
		}
		for( i=1; i<3; i++) {
    
    
			for( j=1; j<i+1; j++) {
    
    
				System.out.print(" ");
			}
			for( j=i; j<5-i; j++) {
    
    
				System.out.print("*");
			}
			System.out.println();
		}

Let's say that hollow diamonds
Hollow diamond
are actually no more difficult than solid ones, but one thing is harder to think about.
When I first started writing, I always thought about how to erase the * in the middle. In fact, it is easy to write in another way of thinking, such as printing only the beginning and end *.

System.out.println("================空心菱形==============");
		int a,b;
		for( a=1; a<4; a++) {
    
    
			for( b=1; b<4-a; b++) {
    
             //每一行先打印空格
				System.out.print(" ");
			}
			for( b=1; b<=2*a-1; b++) {
    
          //再打印 * 
				
				if( b==1 || b==2*a-1) {
    
        //换个思路,只打印第一个和最后一个
					System.out.print("*");
				}
				else {
    
    
					System.out.print(" ");
				}
			}	
			System.out.println();
		}	
		
		for( a=1; a<3; a++) {
    
    
			for( b=1; b<a+1; b++) {
    
    
				System.out.print(" ");
			}
			for( b=a; b<5-a; b++) {
    
    
				if( b==a || b==4-a) {
    
    
					System.out.print("*");
				}
				else {
    
    
					System.out.print(" ");
				}
			}
			System.out.println();
		}

Guess you like

Origin blog.csdn.net/qq_45884783/article/details/104826307