Is there a simple way to wrap a descending number sequence so after a zero the sequence would start again

StackOverflow https://stackoverflow.com/questions/21814065

  •  12-10-2022
  •  | 
  •  

Question

This would be applicable to arrays in situations where the array holds something like banners in a banner carousel. A user clicks two navigation buttons like previous and next. My implementation is :

      public void onClick(View v) {
            if (mCurrentIndex > 0) {mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;} 
            else {mCurrentIndex = mQuestionBank.length - 1;}

Is there a simpler, more elegant way to do this?

Was it helpful?

Solution

I suggest the following technique. It only checks if pointer gets out of boundaries of array and points it either to the end of it or beginning:

public int nextPrev(int mCurrentIndex, int direction) {
   mCurrentIndex = mCurrentIndex + direction;
   if(mCurrentIndex == mQuestionBank.length) {
       mCurrentIndex = 0;
   } else if (mCurrentIndex < 0) {
       mCurrentIndex = mQuestionBank.length - 1;
   } 
   return mCurrentIndex;
}

This will work with direction = 1 or -1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top