Java Enhanced For Loop

How to write the following for loop using the extended 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 to do the following, but I assume I am doing this unsreclty

 for(int i: info){ body here/// 
+4
source share
1 answer

Your syntax is correct. The only difference is that instead of the loop index, the actual value of int i assigned. Thus, if you replace (i+1) % 10 with i % 10 and info[i] with 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 heavy duty cycle, check out this Sun manual .

The above can, by the way, be shortened with the help of a thermal operator ;)

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

Source: https://habr.com/ru/post/1302311/


All Articles