- Home /
Array problem,different result
hi, i'v little trouble with array: if i use:
aa= ( aa + 1 ) % aaList.length;
it's works correctly and when i get last element in array,it returns to frist. but if i use:
aa= ( aa - 1 ) % aaList.length;
and i've the frist element,i get an exception of array. how to solve?
Answer by BiG · Jan 31, 2012 at 08:55 AM
The first instruction is the correct way to iterate through the elements of an array, in a cyclic fashion. In fact it works, as you've said.
The second one, however, is wrong (I think that you're trying to use it to iterate throught the array in a counterclockwise order): when you decrement the first index, you'll obtain "0". The "%" operator on "0" gives "0" as a result, but that's not a legal index for an array. This way, you get the exception.
I don't think that's possible to use such an "elegant" way for the counterclockwise iteration of an array. Just use a normal decrement of the index, and add a test to verify if you've reach the beginning of the array: in that case, you'll assign "aaList.lenght" to "aa".