[英]Can someone explain to me why this nested loop function print this way?
所以這是運行的代碼:
public static void main(String[] args)
{
for (int i=1; i<=6; i++)
{
for (int j=1; j<=i; j++)
System.out.print("*");
System.out.print("-");
}
}
為什么打印
*-**-***-****-*****-******-
代替
* _ ** __ *** ___ **** ____ ***** _____ ****** ______
這是因為沒有將print("-")
放入任何內部循環中,請將循環更改為:
for (int i=1; i<=6; i++)
{
for (int j=1; j<=i; j++)
System.out.print("*");
for (int j=1; j<=i; j++)
System.out.print("-");
}
這樣您的問題就會解決。
System.out.print("-");
不在內部循環內。 因此,對於外循環的每次迭代僅打印一次。
當您正確縮進代碼時,這將變得更加清晰:
for (int i=1; i<=6; i++)
{
for (int j=1; j<=i; j++)
System.out.print("*");
System.out.print("-");
}
即使它在內部循環內(通過添加花括號),您仍將無法獲得預期的輸出,因為每個*
后面都會有一個-
。
為了獲得您期望的輸出,您需要兩個內部循環:
for (int i=1; i<=6; i++)
{
for (int j=1; j<=i; j++)
System.out.print("*");
for (int j=1; j<=i; j++)
System.out.print("-");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.