如果有人想在 java 编程语言方面打下坚实的基础。然后,有必要了解循环的工作原理。此外,解决金字塔模式问题是增强 java 基础知识的最佳方法,因为它包括 for 和 while 循环的广泛使用。本文旨在提供一些 java 程序,借助 java 中可用的不同类型的循环来打印金字塔图案。
我们将通过 Java 程序打印以下金字塔图案 -
倒星金字塔
星金字塔
数字金字塔
立即学习“Java免费学习笔记(深入)”;
让我们一一讨论。

声明并初始化一个指定行数的整数“n”。
接下来,将空间的初始计数定义为 0,将星形的初始计数定义为“n + n – 1”,这样我们就可以保持列数为奇数。
创建一个嵌套的 for 循环,外部循环将运行到“n”,第一个内部 for 循环将打印空格。打印后,我们将在每次迭代时将空间计数增加 1。
再次使用另一个内部 for 循环来打印星星。打印后,我们会将星星数减 2。
public class Pyramid1 {
public static void main(String[] args) {
int n = 5;
int spc = 0; // initial space count
int str = n + n - 1; // initial star count
// loop to print the star pyramid
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= spc; j++) { // spaces
System.out.print("\t");
}
spc++; // incrementing spaces
for(int k = 1; k <= str; k++) { // stars
System.out.print("*\t");
}
str -= 2; // decrementing stars
System.out.println();
}
}
}
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*

声明并初始化一个指定行数的整数“n”。
创建一个嵌套的 for 循环,外部 for 循环将运行到“n”,内部 for 循环将运行到空格数并打印空格。打印后,我们会将空格数减 1。
再次采用另一个内部 for 循环,该循环将运行到星星数并打印星星。打印后,我们会将星星计数增加 2。
public class Pyramid2 {
public static void main(String[] args) {
int n = 5; // number of rows
int spc = n-1; // initial space count
int str = 1; // initial star count
// loop to print the pyramid
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= spc; j++) { // spaces
System.out.print("\t");
}
spc--; // decrementing spaces
for(int k = 1; k <= str; k++) { // stars
System.out.print("*\t");
}
str += 2; // incrementing stars
System.out.println();
}
}
}
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *

我们将在这里使用之前的代码,但我们将打印每行中的列号,而不是打印星星。
public class Pyramid3 {
public static void main(String[] args) {
int n = 5; // number of rows
int spc = n-1; // initial space count
int col = 1; // initial column count
// loop to print the pyramid
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= spc; j++) { // spaces
System.out.print("\t");
}
spc--; // decrementing spaces
for(int k = 1; k <= col; k++) { // numbers
System.out.print(k + "\t");
}
col += 2; // incrementing the column
System.out.println();
}
}
}
1
1 2 3
1 2 3 4 5
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8 9
在本文中,我们讨论了三个打印金字塔图案的 Java 程序。这些模式解决方案将帮助我们解码模式问题的逻辑,并使我们能够自己解决其他模式。为了解决此类模式,我们使用循环和条件块。
以上就是Java程序创建金字塔和图案的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号