ต่อไปนี้เป็นโปรแกรม Java สำหรับพิมพ์รูปแบบ Triangle -
ตัวอย่าง
import java.util.*;
public class Demo{
public static void main(String[] args){
Scanner my_scan = new Scanner(System.in);
System.out.println("Enter the number of rows which needs to be printed");
int my_row = my_scan.nextInt();
for (int i = 1; i <= my_row; i++){
for (int j = my_row; j >= i; j--){
System.out.print(" ");
}
for (int j = 1; j <= i; j++){
System.out.print("^ ");
}
System.out.println();
}
}
} ต้องระบุอินพุตในอินพุตมาตรฐาน − 5
ผลลัพธ์
Enter the number of rows which needs to be printed
^
^ ^
^ ^ ^
^ ^ ^ ^
^ ^ ^ ^ ^ คลาสชื่อ Demo มีฟังก์ชันหลัก ในที่นี้ มีการกำหนดอ็อบเจ็กต์ Scanner และแถวที่จำเป็นจะถูกนำมาจากบรรทัดคำสั่ง การใช้ค่านี้สำหรับ 'แถว' การวนซ้ำจะถูกวนซ้ำ ในทำนองเดียวกัน จำนวนช่องว่างที่ต้องการก็นำมาจากบรรทัดคำสั่งเช่นกัน และจะใช้ระหว่างการพิมพ์สัญลักษณ์ '*' วนซ้ำ 'for' ถูกใช้อีกครั้งเพื่อพิมพ์ '*' ในรูปแบบสามเหลี่ยมบนคอนโซล