java打印金字塔
首先确定每行打印几个空格,在确定每行打印几个*
设总层数为layers,当前层数为i。
则每行打印空格数=layers-i,每行打印星号数=2*i-1
import java.util.Scanner;public class Paremid{public static void main(String[] args) {Scanner myScanner = new Scanner(System.in);int layers = myScanner.nextInt();//输入需要打印的金字塔层数for(int i = 1; i <= layers; i ++){//层数即为循环数for(int j = 1; j <= layers - i; j ++){//每行需要打印的空格数System.out.print(" ");}for(int k = 1; k <= 2 * i - 1; k ++){//每行需要打印的星号数System.out.print("*");}System.out.println();}}
}
打印结果截图:
java打印空心金字塔
import java.util.Scanner;public class KongxinParemid{public static void main(String[] args) {Scanner myScanner = new Scanner(System.in);int layers = myScanner.nextInt();//输入要打印金字塔的总层数//打印前n-1层for(int i = 1; i <= layers - 1; i ++){for(int j = 1; j <= layers - i; j ++){//打印每层之前的空格System.out.print(" ");}for(int k = 1; k <= 2 * i - 1; k ++){//打印空心金字塔内的星号和空格if(k == 1 || k == 2*i-1)//打印第一个星号和最后一个星号System.out.print("*");elseSystem.out.print(" ");}System.out.println();}//打印最后一行for(int z = 1; z <= 2 * layers - 1; z ++){System.out.print("*");}System.out.println();}
}
打印结果截图: