首页 > 文章列表 > Java程序创建金字塔和图案

Java程序创建金字塔和图案

java程序 图案 金字塔
319 2023-09-01

如果有人想在 Java 编程语言方面打下坚实的基础。然后,有必要了解循环的工作原理。此外,解决金字塔模式问题是增强 Java 基础知识的最佳方法,因为它包括 for 和 while 循环的广泛使用。本文旨在提供一些 Java 程序,借助 Java 中可用的不同类型的循环来打印金字塔图案。

创建金字塔图案的 Java 程序

我们将通过 Java 程序打印以下金字塔图案 -

  • 倒星金字塔

  • 星金字塔

  • 数字金字塔

让我们一一讨论。

模式 1:倒星金字塔

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();
      }
   }
}

输出

*  *  *  *  *  *  *  *  *	
   *  *  *  *  *  *  *	
      *  *  *  *  *	
	 *  *  *	
	    *	

图案2:星形金字塔

Java程序创建金字塔和图案

方法

  • 声明并初始化一个指定行数的整数“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();
      }
   }
}

输出

            *	
	 *  *  *	
      *	 *  *  *  *	
   *  *  *  *  *  *  *	
*  *  *  *  *  *  *  *  *	

模式 3:数字金字塔

Java程序创建金字塔和图案

方法

我们将在这里使用之前的代码,但我们将打印每行中的列号,而不是打印星星。

示例

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 程序。这些模式解决方案将帮助我们解码模式问题的逻辑,并使我们能够自己解决其他模式。为了解决此类模式,我们使用循环和条件块。