Wednesday, January 18, 2017

java - Looping through the elements in an array backwards




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]);
}



I'd like to print out the array in descending order, instead of ascending order (from the last element of the array to the first) but I just get thrown this error:



Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at task1.main(task1.java:14)


Why is this happening? I was hoping that by using myArray.length to set the counter to 8, the code would just print out the 8th element of the array and then keep printing the one before that.


Answer




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--) {

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...