java writing pyramid

1. Solid Pyramid

First, try to write a pyramid that adds 1 * layer by layer:
It can be seen that each layer is *composed of spaces and, and 空格+*the total number is the number of cornerstones at the bottom, then the number of spaces before and after is (底部基石数 - 各层星星数)*1/2, and then print the spliced ​​string 空格+*+空格(note : java /will directly round up)
insert image description here
However, in the computer display, each row and column are vertically corresponding, as can be seen from the results in the above figure, adding layer by layer *does not guarantee alignment, but keeping odd rows can get a regular triangular pyramid. Then skip even-numbered lines to print, and you can get a regular triangle pyramid:
insert image description here
the final code is as follows:

public class Test{
    
    
	public static void main(String[] args){
    
    
		int starNum = 7;
		System.out.println("start=" + starNum);
			for(int i = 1; i <= starNum;i += 2){
    
    
				String str = "";
				for(int m=0;m<(starNum - i)/2;m++){
    
    
					str += " ";
				}
				for(int n=0;n<i;n++){
    
    //can change
					str += "*";
				}
				for(int m=0;m<(starNum - i)/2;m++){
    
    
					str += " ";
				}
				System.out.print(str + "\n");
			}
	}
}

2. Average distribution pyramid

Star cross distribution effect:
insert image description here
the code only needs to modify the cycle of printing *position, interval display *and空格

for(int n = 0;n < i;n++){
    
    //can change
	if(n % 2 == 0){
    
    
		str += "*";
	}else{
    
    
		str += " ";
	}
	//或简化成三目运算
	//str += n % 2 == 0 ? "*" : " "; 
}

3. Hollow Pyramid

The edge is *to draw a pyramid shape. The effect is as follows:
insert image description here
Similarly, the code only needs to modify *the cycle of the printing position. In the output *field, the start and end positions are *, the rest of the positions are spaces, and the last line is all*

				for(int n=0;n<i;n++){
    
    //can change
					if(i<starNum){
    
    
						 if((n==0)||(n==i-1)){
    
    
						    str+="*";
						 }else{
    
    
						   str+=" ";
					    }
					    //或者简化为三目运算
					   	//str += n==0||n==i-1?"*":" ";
					}else{
    
    
						str+="*";
					}
				}

Supplement:
Children's shoes from the front end to the back end should pay attention . In java, the ternary operator cannot write assignment statements in it, which is different from js. For example (n > 2) ? (str = "*") : (str = "%");, the front-end js of this sentence can be compiled and passed, but if it is placed in java, it will fail to compile and report an error: not a statement. It should be written like this in java:str = n > 2 ? "*" : "%"

Guess you like

Origin blog.csdn.net/weixin_43939111/article/details/131307299