x


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?

more ▼

asked Jan 30 '12 at 07:20 PM

devilkkw gravatar image

devilkkw
297 7 10 18

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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".

more ▼

answered Jan 31 '12 at 08:55 AM

BiG gravatar image

BiG
4.7k 4 13 49

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1359
x255
x128

asked: Jan 30 '12 at 07:20 PM

Seen: 343 times

Last Updated: Jan 31 '12 at 08:55 AM