ในบทความนี้ เราจะเข้าใจวิธีการพิมพ์ลวดลายรูปดาวสามเหลี่ยมมุมฉากกลวง รูปแบบถูกสร้างขึ้นโดยใช้คำสั่ง for-loop และการพิมพ์หลายรายการ สำหรับพีระมิดที่บรรทัดแรก จะพิมพ์ดาวหนึ่งดวง และบรรทัดสุดท้ายจะพิมพ์ดาวจำนวน 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 * ** * * * * * * * * * * ********