Java 程式列印方形星形圖案


在本文中,我們將瞭解如何列印方形星形圖案。該圖案由多個 for 迴圈 和列印語句構成。

以下是相同的演示 −

輸入

假設我們的輸入是 −

Enter the length of a side : 8

輸出

期望的輸出為 −

The square pattern :
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *

演算法

Step 1 - START
Step 2 - Declare three integer values namely i, j and my_input
Step 3 - Read the required values from the user/ define the values
Step 4 - We iterate through two nested 'for' loops 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

在此,輸入由使用者根據 8a 提示輸入。你可以在我們的 編碼平臺工具 執行按鈕 中線上執行此示例。

import java.util.Scanner;
public class SquarePattern{
   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 length of a side : ");
      my_input = my_scanner.nextInt();
      System.out.println("The square pattern : ");
      for(i = 1; i <= my_input; i++){
         for(j = 1; j <= my_input; j++){
            System.out.print("*");
         }
         System.out.print("\n");
      }
   }
}

輸出

Required packages have been imported
A reader object has been defined
Enter the length of a side : 8
The square pattern :
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *

示例 2

此處,整數已經事先定義,在控制檯中訪問並顯示其值。

public class SquarePattern{
   public static void main(String args[]){
      int i, j, my_input;
      my_input = 8;
      System.out.println("The length of a side is defined as " +my_input);
      System.out.println("The square pattern : ");
      for(i = 1; i <= my_input; i++){
         for(j = 1; j <= my_input; j++){
            System.out.print("* ");
         }
         System.out.print("\n");
      }
   }
}

輸出

The length of a side is defined as 8
The square pattern :
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *

更新於: 2024 年 5 月 31 日

11K+ 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

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