Positive Triangle Code:
1 PackageBasictype;2 /**3 * Encapsulates a method that can print a positive triangle based on the user's incoming value4 * @authorAdministrator5 */6 7 Public classEnme {8 //N represents the number of layers printed9 Public Static voidPrint_positive_triangle (intN) {Ten //the first layer 1, the second layer three, the third layer 5 ... The analogy exits the nth layer is the last one * One intLast = +1 (n-1); A //control how many layers are printed - for(inti=0;i<n;i++) -{//calculates the number of spaces to be filled to the left of each layer the intFull_left = last/2-i; - //a newline is required after printing a layer -System.out.println (""); - //controls the style to be printed on this layer, by default printing out squares + for(intj=0;j<=last;j++){ - //If J is less than the number of spaces to be filled or equal or j is greater than the number of positions occupied by * and the number of places the space is filled with, the space is printed + if(j<=full_left| | J>full_left+2*i+1){ ASystem.out.print (""); at } - Else{ -System.out.print ("*"); - } - } - } in } - to Public Static voidMain (string[] args) { +Print_positive_triangle (5); - } the}
Inverted Triangle Code:
1 Public classEnme {2 3 //Print Inverted triangle4 Public Static voidPrint_nagative_triangle (intN) {5 //The maximum number of * of the layer *6 intLast = 2*n-1;7 //control how many layers are printed8 for(inti=n-1;i>=0;i--)9{//calculates the number of spaces to be filled to the left of each layerTen intFull_left = n-i-1; OneSystem.out.println (""); A for(intj=0;j<last;j++){ - if(j<full_left| | J>=full_left+2*i+1){ -System.out.print (""); the } - Else{ -System.out.print ("*"); - } + } - } + } A at Public Static voidMain (string[] args) { - //Print_positive_triangle (5); -Print_nagative_triangle (5); - } -}
Java Implementation print Positive triangle