简体   繁体   中英

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 :

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("-");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM