Java 程序打印倒五角星图案
在本文中,我们将了解如何打印倒五角星图案。该图案是使用多个 for 循环和 print 语句形成的。
以下是演示代码 −
输入
假设我们的输入为 −
Enter the size : 8
输出
所需的输出为 −
The inverted 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 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 InvertedStar{ 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(); System.out.println("The inverted star pattern"); for ( i = my_input ; i >= 1; i-- ){ for ( j = 0 ; j < my_input - i; j++ ){ System.out.print(" "); } for ( k = 0 ; k != (2 * i) - 1; k++ ){ System.out.print("*"); } System.out.println(); } } }
输出
Required packages have been imported A reader object has been defined Enter the size : 8 The inverted star pattern *************** ************* *********** ********* ******* ***** *** *
示例 2
在此处,整数已预先定义,并访问其值并显示在控制台中。
public class InvertedStar{ public static void main(String[] args){ int my_input, k, i, j; char my_character; my_input = 8; System.out.println("The size is defined as " +my_input); System.out.println("The inverted star pattern"); for ( i = my_input ; i >= 1; i-- ){ for ( j = 0 ; j < my_input - i; j++ ){ System.out.print(" "); } for ( k = 0 ; k != (2 * i) - 1; k++ ){ System.out.print("*"); } System.out.println(); } } }
输出
The size is defined as 8 The inverted star pattern *************** ************* *********** ********* ******* ***** *** *
广告