Java 程序以打印半菱形星形图案
在本文中,我们将了解如何打印半菱形星形图案。该图案通过使用多个 for 循环和 print 语句来形成。
以下是相同示例的演示 −
输入
假设我们的输入是 −
Enter the number of rows : 8
输出
所需输出为 −
The half diamond 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
在这里,输入是由用户根据提示输入的。您可以在我们的 编码基础工具 中实时尝试此示例。
import java.util.Scanner; public class HalfDiamond{ 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.print("The half diamond pattern : "); for (i = 0; i < my_input; i++){ for (j = 0; j < i + 1; j++) System.out.print("*"); System.out.print("\n"); } for (i = 1; i < my_input; i++){ for (j = i; j < my_input; j++) System.out.print("*"); System.out.print("\n"); } } }
输出
Required packages have been imported A reader object has been defined Enter the number of rows : 8 The half diamond pattern : * ** *** **** ***** ****** ******* ******** ******* ****** ***** **** *** ** *
示例 2
在这里,整数已预先定义,并且其值在控制台上被访问和显示。
public class HalfDiamond{ 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.print("The half diamond pattern : "); for (i = 0; i < my_input; i++){ for (j = 0; j < i + 1; j++) System.out.print("*"); System.out.print("\n"); } for (i = 1; i < my_input; i++){ for (j = i; j < my_input; j++) System.out.print("*"); System.out.print("\n"); } } }
输出
The number of rows is defined as 8 The half diamond pattern : * ** *** **** ***** ****** ******* ******** ******* ****** ***** **** *** ** *
广告