Java Enhanced For Loop

蓝咒 提交于 2021-01-27 06:48:08

问题


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///

回答1:


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 + ", ");
}

To learn more about the enhanced for loop, check this Sun guide.

The above can by the way be shortened with help of the ternary operator ;)

int[] info = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i : info) {
    System.out.println(i + (i % 10 == 0 ? "" : ", "));
}


来源:https://stackoverflow.com/questions/2330891/java-enhanced-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!