JAVA-print asterisk triangle

1. Subject requirements

Define a static method printStar in the class. This method has no return value and needs an integer parameter number. Call this method in the main method, call this method, and enter the value 6 and the value 10 to get the result as shown in the figure below.
6
10

Two, problem-solving ideas

Through observation, we can find that the number of spaces in front of each line is equal to the total number of lines-the current number of lines. After that, we can conclude that except for the first and last two lines, the lines in the middle are all marked with an asterisk, and then the space is marked with an asterisk. So you can use the if statement to judge these three situations:
① Print an asterisk on the first line.
②Print 2xnumber-1 (number of total lines) asterisks in the last line.
③In other cases, print an asterisk, then print 2xi-3 (i is the current line number) spaces, and then print an asterisk.
After the flow control structure is clear, we can start writing code~

Three, code implementation

Define static printStar method

class A{
    
    
	public static void printStar(int number){
    
    
		for(int i=1;i<=number;i++) {
    
    
			for(int m=0;m<number-i;m++) {
    
    
				System.out.print(" ");
			}
			if(i==1) {
    
    
				System.out.println("*");
			}
			else if(i==number) {
    
    
				for(int n=1;n<=2*number-1;n++) {
    
    
					System.out.print("*");
				}
				System.out.println("\n");
			}
			else {
    
    
				System.out.print("*");
				for(int p=1;p<=2*i-3;p++) {
    
    
					System.out.print(" ");
				}
				System.out.println("*");
			}
		}
	}
}

Call in the test class

public class Test {
    
    

	public static void main(String[] args) {
    
    
		
		//A类静态方法调用(直接调用)
		A.printStar(6);
		//A类非静态方法调用(需新建对象),即将方法头的static关键字去掉,方法名重命名为unprintStar
		A star=new A();
		star.unprintStar(10);
	}
}

Four, running results

Star triangle
The overall implementation is like this~ If there are friends who are not clear about static and non-static methods, please leave a message to discuss!

Guess you like

Origin blog.csdn.net/Crush_wen/article/details/109301288