Java程式列印左三角形星號圖案


在這篇文章中,我們將學習如何使用Java列印左三角形星號圖案。該圖案是使用多個for迴圈和print語句形成的。

問題陳述

編寫一個Java程式來列印左三角形星號圖案。以下是演示:

輸入

Enter the number of rows : 8

輸出

The right triangle star pattern : 
                 * 
               * * 
             * * * 
           * * * * 
         * * * * * 
       * * * * * * 
     * * * * * * * 
   * * * * * * * * 

不同的方法

以下是使用Java列印左三角形星號圖案的步驟:

使用預定義輸入

以下是列印左三角形星號圖案的步驟:

  • 定義一個整數變數來表示行數。
  • 使用巢狀for迴圈來列印左三角形圖案中每一行的空格和星號。

示例

這裡,整數已預先定義,其值被訪問並顯示在控制檯上:

public class RightTriangle{
   public static void main(String args[]){
      int i, j, my_input;
      my_input = 8;
      System.out.println("The number of rows is defined as " +my_input);
      System.out.println("The right triangle star pattern : ");
      for (i=0; i<my_input; i++){
         for (j=2*(my_input-i); j>=0; j--){
            System.out.print(" ");
         }
         for (j=0; j<=i; j++ ){
            System.out.print("* ");
         }
         System.out.println();
      }
   }
}

輸出

The number of rows is defined as 8
The right triangle star pattern : 
                 * 
               * * 
             * * * 
           * * * * 
         * * * * * 
       * * * * * * 
     * * * * * * * 
   * * * * * * * * 

使用使用者定義輸入

以下是列印左三角形星號圖案的步驟:

  • java.util包匯入Scanner類以接受使用者輸入。
  • 建立一個Scanner物件,並提示使用者輸入行數。
  • 使用**巢狀for迴圈**來控制每一行列印的行數、空格和星號。

示例

這裡,輸入是基於提示由使用者輸入的:

import java.util.Scanner;
public class RightTriangle{
   public static void main(String args[]){
      int i, j, my_input;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the number of rows : ");
      my_input = my_scanner.nextInt();
      System.out.println("The right triangle star pattern : ");
     for (i=0; i<my_input; i++){
        for (j=2*(my_input-i); j>=0; j--){
           System.out.print(" ");
        }
        for (j=0; j<=i; j++ ){
           System.out.print("* ");
        }
        System.out.println();
     }
   }
}

輸出

Required packages have been imported
A reader object has been defined
Enter the number of rows : 8
The right triangle star pattern : 
                 * 
               * * 
             * * * 
           * * * * 
         * * * * * 
       * * * * * * 
     * * * * * * * 
   * * * * * * * * 

更新於:2024-11-14

699 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.