Java 创建金字塔和图案

Java 创建金字塔和图案

如果有人想在Java编程语言中建立一个坚实的基础,了解循环的工作机制是必要的。解决金字塔图案问题是增强Java基础的最佳方法,因为它包括了对for循环和while循环的广泛使用。本文旨在利用Java中可用的不同类型的循环来提供一些打印金字塔图案的Java程序。

创建金字塔图案的Java程序

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

  • 倒置星形金字塔

  • 星形金字塔

  • 数字金字塔

让我们逐一讨论它们。

图案1:倒置星形金字塔

Java 创建金字塔和图案

方法

  • 声明并初始化一个整数’n’,指定行数。

  • 接下来,将初始空格计数为0,初始星号计数为’n + n – 1’,以便我们可以保持列数为奇数。

  • 创建一个嵌套的for循环,外部循环将运行到’n’,第一个内部循环将打印空格。打印后,我们将每次迭代将空格计数增加1。

  • 再次进行另一个内部循环,它将打印星号。打印后,我们将星号计数减少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”,表示行数。

  • 创建嵌套循环,外部循环将循环到“n”,内部循环将循环到空格数并打印空格。打印完后,将空格计数减1。

  • 再次创建一个内部循环,该循环将循环到星号数并打印星号。打印完后,将星号计数增加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程序。这些模式解决方案将帮助我们解码模式问题的逻辑,并使我们能够自己解决其他模式。要解决这样的模式,我们使用循环和条件块。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程