更新時(shí)間:2022-06-16 10:45:05 來源:動(dòng)力節(jié)點(diǎn) 瀏覽1472次
如何用Java打印三角形圖案?動(dòng)力節(jié)點(diǎn)小編告訴你。給定一個(gè)數(shù)字 N,任務(wù)是打印以下模式:
例子:
輸入:10
輸出 :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
輸入:5
輸出 :
*
* *
* * *
* * * *
* * * * *
打印上述模式需要一個(gè)嵌套循環(huán)。外部循環(huán)用于運(yùn)行作為輸入給出的行數(shù)。外循環(huán)中的第一個(gè)循環(huán)用于打印每個(gè)星之前的空格。正如你所看到的,當(dāng)我們向三角形的底部移動(dòng)時(shí),每一行的空格數(shù)都會(huì)減少,所以這個(gè)循環(huán)在每次迭代中運(yùn)行的時(shí)間減少了一次。外循環(huán)中的第二個(gè)循環(huán)用于打印星星。正如你所看到的,隨著我們向三角形底部移動(dòng),每行中的星數(shù)增加,所以這個(gè)循環(huán)在每次迭代中多運(yùn)行一次。如果該程序是空運(yùn)行的,則可以實(shí)現(xiàn)清晰度。
// 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();
}
}
}
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)