Java 程式用於列印映象上星三角形圖案


在本文中,我們將瞭解如何列印映象上星三角形圖案。該圖案是使用多個 for 迴圈和 print 語句形成的。

下面展示了演示步驟 −

輸入

假設我們的輸入為 −

Enter the number of rows : 8

輸出

所需的輸出為 −

The mirror upper star pattern :
********
 *******
  ******
   *****
    ****
     ***
      **
       *

演算法

Step 1 - START
Step 2 - Declare four integer values namely i, j, k and my_input
Step 3 - Read the required values from the user/ define the values
Step 4 - We iterate through two nested 'for' loops inside a ‘for’ loop to get space between the characters.
Step 5 - After iterating through the innermost loop, we iterate through another 'for' loop. This will help print the required character.
Step 6 - Now, print a newline to get the specific number of characters in the subsequent lines.
Step 7 - Display the result
Step 8 - Stop

示例 1

此處,輸入是由使用者根據提示輸入的。您可以在我們的 程式碼練習工具 執行按鈕 中嘗試此示例。

import java.util.Scanner;
public class MirrorTriangle{
   public static void main(String args[]){
      int i, j, k, 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 mirror upper star pattern: ");
      for (i= my_input; i>= 1; i--){
         for (j=my_input; j>i;j--){
            System.out.print(" ");
         }
         for (k=1;k<=i;k++){
            System.out.print("*");
         }
         System.out.println("");
      }
   }
}

輸出

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

示例 2

此處,此整數已預先定義,並且其值在控制檯上進行訪問和顯示。

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

輸出

The number of rows is defined as 8
The mirror upper star pattern:
********
 *******
  ******
   *****
    ****
     ***
      **
       *

更新時間:2022-2-25

399 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.