[英]Can someone explain to me why this nested loop function print this way?
So here is the code that runs: 所以这是运行的代码:
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("-");
}
}
why does it print 为什么打印
*-**-***-****-*****-******- *-**-***-****-*****-******-
instead of 代替
* _ ** __ *** ___ **** ____ *****_____******______ * _ ** __ *** ___ **** ____ ***** _____ ****** ______
this is because didnt put your print("-")
inside any of your inner loops, change your loop to : 这是因为没有将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("-");
}
and your problem will fix. 这样您的问题就会解决。
System.out.print("-");
is not inside the inner loop. 不在内部循环内。 Therefore it's only printed once for each iteration of the outer loop. 因此,对于外循环的每次迭代仅打印一次。
This becomes clearer when you indent your code properly : 当您正确缩进代码时,这将变得更加清晰:
for (int i=1; i<=6; i++)
{
for (int j=1; j<=i; j++)
System.out.print("*");
System.out.print("-");
}
Even if it was inside the inner loop (by adding curly braces), you'd still not get the output you expected, since you'll get one -
after each *
. 即使它在内部循环内(通过添加花括号),您仍将无法获得预期的输出,因为每个*
后面都会有一个-
。
In order to get the output you expected, you need two inner loops : 为了获得您期望的输出,您需要两个内部循环:
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.