更新時間:2022-06-16 10:45:05 來源:動力節點 瀏覽1405次
如何用Java打印三角形圖案?動力節點小編告訴你。給定一個數字 N,任務是打印以下模式:
例子:
輸入:10
輸出 :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
輸入:5
輸出 :
*
* *
* * *
* * * *
* * * * *
打印上述模式需要一個嵌套循環。外部循環用于運行作為輸入給出的行數。外循環中的第一個循環用于打印每個星之前的空格。正如你所看到的,當我們向三角形的底部移動時,每一行的空格數都會減少,所以這個循環在每次迭代中運行的時間減少了一次。外循環中的第二個循環用于打印星星。正如你所看到的,隨著我們向三角形底部移動,每行中的星數增加,所以這個循環在每次迭代中多運行一次。如果該程序是空運行的,則可以實現清晰度。
// Java Program to print the given pattern
import java.util.*; // package to use Scanner class
class pattern {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows to be printed");
int rows = sc.nextInt();
// loop to iterate for the given number of rows
for (int i = 1; i <= rows; i++) {
// loop to print the number of spaces before the star
for (int j = rows; j >= i; j--) {
System.out.print(" ");
}
// loop to print the number of stars in each row
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
// for new line after printing each row
System.out.println();
}
}
}
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習