[英]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. 因为
k
从0
开始,并且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.