Here's my code:
int myArray[]={1,2,3,4,5,6,7,8};
for(int counter=myArray.length; counter > 0;counter--){
System.out.println(myArray[counter]);
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at task1.main(task1.java:14)
Arrays in Java are indexed from 0
to length - 1
, not 1
to length
, therefore you should be assign your variable accordingly and use the correct comparison operator.
Your loop should look like this:
for(int counter=myArray.length - 1; counter >= 0;counter--){