简体   繁体   English

谁能给我解释一下Java中关于内存的嵌套for循环的行为?

[英]Can anyone explain to me the behavior of a nested for loop in Java in regards to memory?

Let's suppose I have this code which also print a pattern of star (that is if I replace the string literal in side the print method with "#") like a staircase going from right to left below. 假设我有这段代码,它也可以打印一个星形模式(即,如果我在打印方法的侧面用“#”替换字符串文字),就像从右下往下走的楼梯。

public static void main(String[] args) 
{
    for (int i=0; i <= 6; i++){
        for(int k=0; k < i; k++){
            System.out.print("This is k:"+k + " " + " This is i:"+i);
        }

        System.out.println();
    }


}

This will actually prints all 0s for the values of k in each column, then prints all 1s, then all 2s etc...For the value of i it will print in each column 1,2,3,4,5,6 then 2,3,4,5,6 the 3,4,5,6 etc.. 实际上,这将在每列中将k的值全部打印为0,然后再将所有1s,然后所有2s依次打印出来...对于i的值,它将在每列1,2,3,4,5,6中打印,然后2,3,4,5,6 3,4,5,6等。

Ok, why is the value of i does not start at zero here? 好的,为什么i的值不是从零开始? I thought the inside loop is supposed to execute first. 我以为应该先执行内部循环。

This has nothing to do with memory, just logic. 这与内存无关,只是逻辑。 Because k starts at 0 , and k < i means the first test is 0 < 0 which isn't true. 因为k0开始,并且k < i意味着第一个测试是0 < 0 ,这是不正确的。 So i increments. 所以i增加。 Thus your first i output is 1 . 因此,您的第一个i输出为1 If you want to see 0 for i , you need k <= i in your inner for loop condition. 如果要为i看到0 ,则在内部for循环条件中需要k <= i

Instead of this you should start your value of i from 1 取而代之的是,您应该i from 1开始计算i from 1的值

for(i=1;i<6;i++)

As you are not achieving anything with i=0 except println . 因为除了println之外, i=0并没有实现任何目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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