Java增强的For循环 [英] Java Enhanced For Loop
本文介绍了Java增强的For循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用增强的for循环编写以下for循环>
How would I write the following for loop using an enhanced for loop>
int [] info = {1,2,3,4,5,6,7,8,9,10};
int i;
for (i = 0; i < info.length; i++) {
if ((i+1) % 10 == 0)
System.out.println(info[i]);
else
System.out.println(info[i] + ", ");
}
我正在尝试以下操作,但我想我是不正确地这样做
I am trying the following, but i guess im doing it incorreclty
for(int i: info){
body here///
推荐答案
您的语法正确.区别仅在于,您是将实际int值分配给 i
而不是循环索引.因此,如果您将(i + 1)%10
替换为 i%10
,将 info [i]
替换为 i
,它将正常工作.
Your syntax is correct. The difference is only that you're assigning the actual int value to i
instead of the loop index. Thus, if you replace (i+1) % 10
by i % 10
and info[i]
by i
, it will work correctly.
int[] info = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i : info) {
if (i % 10 == 0)
System.out.println(i);
else
System.out.println(i + ", ");
}
要了解有关增强的for循环的更多信息,请检查此Sun指南.
To learn more about the enhanced for loop, check this Sun guide.
通过三元运算符;)
int[] info = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i : info) {
System.out.println(i + (i % 10 == 0 ? "" : ", "));
}
这篇关于Java增强的For循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文