java 打印金字塔
程序员文章站
2022-04-22 19:38:08
...
一个java示例打印半完整金字塔,以供乐趣。
package com.mkyong;
import java.util.Collections;
public class CreatePyramid {
public static void main(String[] args) {
int rows = 5;
System.out.println("\n1. 半凌锥\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
System.out.println("");
}
System.out.println("\n2. 全金字塔\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows - i; j++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println("");
}
//java 8 , one line
System.out.println("\n3. 完整金字塔\n");
for (int i = 0; i < rows; i++) {
System.out.println(String.join("", Collections.nCopies(5 - i - 1, " "))
+ String.join("", Collections.nCopies(2 * i + 1, "*")));
}
// java 8
System.out.println("\n4. 倒金字塔\n");
for (int i = rows; i > 0; i--) {
System.out.println(String.join("", Collections.nCopies(5 - i, " "))
+ String.join("", Collections.nCopies(2 * i - 1, "*")));
}
}
}
控制台输出
1. 半凌锥
*
**
***
****
*****
2. 全金字塔
*
* *
* * *
* * * *
* * * * *
3. 完整金字塔
*
***
*****
*******
*********
4. 倒金字塔
*********
*******
*****
***
*
转载自http://www.mkyong.com/java/java-how-to-print-a-pyramid/
上一篇: 把雨涮都给骂启动了