Java – reverse loop for array countdown
•
Java
I received an error
Exception in thread "main" java.lang.Arrayindexoutofboundsexception: 10 at Reverse.main(Reverse.java:20).
The syntax is correct, so I'm not sure why there are errors when compiling?
public class Reverse { public static void main(String [] args){ int i,j; System.out.print("Countdown\n"); int[] numIndex = new int[10]; // array with 10 elements. for (i = 0; i<11 ; i++) { numIndex[i] = i;// element i = number of iterations (index 0=0,1=1,ect.) } for (j=10; j>=0; j--){ // Could have used i,doesn't matter. System.out.println(numIndex[j]);//indexes should print in reverse order from here but it throws an exception? } }
}
Solution
Java uses 0 - based array indexes When you create an array of int new [10] with a size of 10, it will create 10 integer 'units' in the array The index is: 0,1,2, 8,9.
Your cycle counts to an index that is less than 11 or 10 and does not exist
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码