for循环没有在java中的大括号 [英] for loop without braces in java

查看:464
本文介绍了for循环没有在java中的大括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么这两个代码给出了不同的结果;

pre> for(i = 1,j = 0; i< ; 10; i ++){
j + = i;
System.out.println(i);





这个数字给出了1个包含的数字和10个被排除的数字。对于(i = 1,j = 0; i <10; i ++)
j + = i,

  
System.out.println(i);

然而这个给出了10.我无法得到这个逻辑;

  for()
do_something;
do_something_else;


解决方案

这是因为迭代的默认范围是只有跟在它后面的行,在你的情况下,相当于 - ($ = $,$,$,$,$,$,$,$,$,$,$) ; i ++){
j + = i;
}
System.out.println(i);

因此整个循环都是迭代的,从那以后i == 10的值,就是你的在第二种情况下输出。




在第一种情况下,非常明显的是每次迭代打印值1至9(小于10):对于(i = 1,j = 0; i <10; i ++){b
$ b

  
j + = i;
System.out.println(i);
}


I wonder why this two following codes give different results;

for(i = 1, j = 0; i < 10; i++) {
    j += i;
    System.out.println(i);
}

This one gives the numbers between 1 included and 10 excluded.

for(i = 1, j = 0; i < 10; i++)
    j += i;
System.out.println(i);

However this one gives 10. I could not get the logic of this;

for()
do_something;
do_something_else;

解决方案

That is because the default scope of an iteration is the only following line after it, in your case something equivalent to -

for(i=1, j=0;i<10;i++) {
    j += i;
}
System.out.println(i);

Hence the entire loop is iterated and since after that the value of i==10, that is your output in the second case.


In the first case, it's pretty obvious that the value is printed with each iteration and hence 1 to 9(less than 10) :

for(i=1, j=0;i<10;i++){
    j += i;
    System.out.println(i);
}

这篇关于for循环没有在java中的大括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆