I have this very little program in Java (just started to learn this language):
package hellojava;
public class Hellojava {
public static void main(String[] args) {
System.out.println("Hello World");
int[] nums = {1,2,3,4,5,6,7,8,9,10};
int[] revs = reverse(nums);
for (int i : revs) {
System.out.println(revs[i]);
}
}
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i=0, j=result.length-1; i<list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
}
It throws this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at hellojava.Hellojava.main(Hellojava.java:9).
So I pretty know what's wrong and know how to fix it, but my question is about that for loop. I thought that this enhanced for loop will work here, but it doesn't. Why's that?