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打印空心金字塔
方法1:先打印前n-1层(在k循环处只打印第一个星号和最后一个星号),最后一层单独循环全打印星号
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("*");
else
System.out.print(" ");
}
System.out.println();
}
//打印最后一行
for(int z = 1; z <= 2 * layers - 1; z ++){
System.out.print("*");
}
System.out.println();
}
}
方法2:每一行都采用同循环,在k循环处只打印第一个星号和最后一个星号,且如果i=总层数,打印星号
import java.util.Scanner;
public class KongxinParemid{
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int layers = myScanner.nextInt();// input total layer
for(int i = 1; i <= layers - 1; i ++){//first layers-1 rows
for(int j = 1; j <= layers - i; j ++){//space number
System.out.print(" ");
}
for(int k = 1; k <= 2 * i - 1; k ++){
if(k == 1 || k == 2*i-1 || i == layers)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}
打印结果截图: