Java程式列印空心直角三角形星號圖案
在這篇文章中,我們將學習如何列印空心直角三角形星號圖案。該圖案是透過使用多個for迴圈和print語句形成的。第一行金字塔將列印一顆星,最後一行將列印n顆星。其他行將在行的開頭和結尾處列印正好兩顆星,這兩顆星之間將有一些空格。
以下是相同的演示 -
輸入
假設我們的輸入是 -
Enter the size : 8
輸出
期望的輸出將是 -
The hollow pyramid triangle : * * * * * * * * * * * ********
演算法
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 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 Hollowtangle{ public static void main(String[] args){ int my_input, k, i, j; 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 size : "); my_input = my_scanner.nextInt(); for( i=1;i<=my_input;i++){ if(i==1 || i==my_input) for( j=1;j<=i;j++){ System.out.print("*"); } else { for( j=1;j<=i;j++){ if(j==1 || j==i) System.out.print("*"); else System.out.print(" "); } } System.out.println(); } } }
輸出
Required packages have been imported A reader object has been defined Enter the size : 8 ** * * * * * * * * * * ********
示例2
這裡,整數已預先定義,其值在控制檯中被訪問和顯示。
public class Hollowtangle{ public static void main(String[] args){ int my_input, i, j; my_input = 8; System.out.println("The size is defined as " +my_input); for( i=1;i<=my_input;i++){ if(i==1 || i==my_input) for( j=1;j<=i;j++){ System.out.print("*"); } else { for( j=1;j<=i;j++){ if(j==1 || j==i) System.out.print("*"); else System.out.print(" "); } } System.out.println(); } } }
輸出
The size is defined as 8 * ** * * * * * * * * * * ********
廣告