Why don't Java for loops work the same way?

public static int[] plusOne(int[] digits) {
   long n = 0;
   for(int i = 0; i < digits.length; i++) {
     n = n*10+digits[i];
   }
   System.out.println(n);
   n = 0; 
   for(int i : digits) {
     n = n*10+digits[i];
   }
   System.out.println(n);
   return digits;
}

The above code for me prints entirely different numbers for n depending on which loop I use. The first one prints out "9876543210" and the second one prints out "123456789". My input array is "{9,8,7,6,5,4,3,2,1,0}." I am changing the int[] array to a single value and expected output is the result of the classic for loop "9876543210". My understanding is that these should work essentially the same way.

>Solution :

This line will count indexes for you:

for(int i = 0; i < digits.length; i++)

and you have to get to the real number by looking it up:

int digit = digits[i];
n = n*10+digit;

While that expression will directly give you the numbers you are interested in:

for(int digit : digits) {

so you do not look up up but use it directly:

n = n*10+digit;

Leave a Reply