java打印菱形
菱形分上下两个部分。其中上部分同打印金字塔;下部分循环部分i是递减
(ps:菱形层数只能为奇数)
import java.util.Scanner;
public class Lingxing{
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.print("please input lingxing layers(odd number):");
int layers = myScanner.nextInt();
int mid = layers / 2 + 1;//层数的一半,向上取整,eg.layers = 5,mid = 3
//打印上半部分(即金字塔)
for(int i = 1; i <= mid; i ++){//上半部分循环次数
for(int j = 1; j <= mid - i; j ++){
System.out.print(" ");
}
for(int k = 1; k <= 2 * i - 1; k ++){
System.out.print("*");
}
System.out.println();
}
//打印下半部分
for(int i = layers; i >= mid; i --){//下半部分循环次数
//如果i++的话,星号数和layers和i没有关系
for(int j = 1; j <= layers - i + 1; j ++){//打印空格数
System.out.print(" ");
}
for(int k = 1; k <= 2 * (i - mid) - 1; k ++){//打印*数
System.out.print("*");
}
System.out.println();
}
}
}
打印结果截图如下:
java打印空心菱形
菱形分上下两个部分。其中上部分同打印空心金字塔;
下半部分同打印星号同空心菱形
(ps:菱形层数只能为奇数)
import java.util.Scanner;
public class KongxinLingxing{
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.print("please input KongxinLingxing layers(odd number):");
int layers = myScanner.nextInt();
int mid = layers / 2 + 1;//层数的一半,向上取整,eg.layers = 5,mid = 3
//打印上半部分(即空心金字塔)
for(int i = 1; i <= mid; i ++){//first layers-1 rows
for(int j = 1; j <= mid - i; j ++){//space number
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 i = layers; i >= mid; i --){//如果i++的话,星号数和layers和i没有关系
for(int j = 1; j <= layers - i + 1; j ++){
System.out.print(" ");
}
for(int k = 1; k <= 2 * (i - mid) - 1; k ++){
if(k == 1 || k == 2 * (i - mid) - 1)//打印第一个*和最后一个*
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}