Java for循环很难理解

时间:2017-03-23 09:51:51

标签: java loops

有人可以向我解释为什么以下代码块会产生不同的输出吗?

public class hello 
{

    public static void main(String args[])
    {
        int a,b,c;
        for (a  = 0; a < 5; a++)
        {
            for (b = 4; b >= a; b--)
            {
                System.out.print(" ");
            }
            for (c = 0; c <= a - b; c++)
            {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

输出:

enter image description here

public class hello 
{

    public static void main(String args[])
    {
        int a,b,c;
        for (a  = 0; a < 5; a++)
        {
            for (b = 4; b >= 0; b--)
            {
                System.out.print(" ");
            }
            for (c = 0; c <= a - b; c++)
            {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

输出:

enter image description here

输出是否应该相同,因为b> = a等于b> = 0,因为对于每个循环,b的值将减去1?

3 个答案:

答案 0 :(得分:2)

变量a将从0变为4,因此对于每次迭代,您将拥有:

for (b = 4; b >= 0; b--)
    { [...]

for (b = 4; b >= 1; b--)
    { [...]

for (b = 4; b >= 2; b--)
    { [...]

答案 1 :(得分:2)

不,每次执行时输出都不能相同

A1:C4 B2:D3 B1:B6

这也会被执行(5次)

for (a = 0; a < 5; a++)

但是for (b = 4; b >= a; b--) { System.out.print(" "); } 的值随着每次迭代而变化:a最初为0,然后是1,2,3,最后是4。

因此,您在第一个场景中打印的空格数将随着a的每次迭代而减少。

  

对于a = 0,我们有:       b = 4,       b = 3,       b = 2,       b = 1,       b = 0(a停止,因为b = -1不是&gt; = a = 0)

     

对于a = 1,我们有:       b = 4,       b = 3,       b = 2,       b = 1(for loop停止,因为b = 0不是&gt; = a = 1)

     

对于a = 2,我们有:       b = 4,       b = 3,       b = 2(for loop停止,因为b = 1不是> = a = 2)

     

对于a = 3,我们有:       b = 4,       b = 3(for loop停止,因为b = 2不是> = a = 3)

     

对于a = 4,我们有:       b = 4(for loop停止,因为b = 3不是> = a = 4)

答案 2 :(得分:1)

请阅读代码中的注释,您将获得不同之处!

    int a, b, c;
    for (a = 0; a < 5; a++)
    {
        for (b = 4; b >= a; b--) // Print every time b-a + 1 underscores... since you start every time with b=4 you have for each a one space fewer
        {
            System.out.print(" ");
        }

        for (c = 0; c <= a - b; c++) // and then print (a-b)-c +1 stars (b is every time a-1)... 
                                     // (first a=0 -b=-1)+1=2 and any time it will prit 2 stars scince
        {
            System.out.print("*");
        }
        System.out.println();
    }

    for (a = 0; a < 5; a++)
    {
        for (b = 4; b >= 0; b--) // Print every time b-a + 1=4 underscores
        {
            System.out.print(" ");
        }

        for (c = 0; c <= a - b; c++) // and then print (a-b)-c +1 stars (b is every time -1)... 
                                     // first time ( a=0 -b=-1)+1 =2 , second time (a=1 - b=-1)+1=3
        {
            System.out.print("*");
        }

        System.out.println();
    }