Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading