Alternative method for getting index of previous question?


#1

I did the challenge of adding the previous button to GeoQuiz but I feel my code is kinda stupid. Here is how i did it:

[code] mPrevButton = (Button)findViewById(R.id.prev_button);
mPrevButton.setOnClickListener(new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			mCurrentIndex = (mCurrentIndex == 0) ? mQuestionBank.length - 1 : mCurrentIndex - 1;
			updateQuestion();
		}
	});[/code]

Is there any alternative/Better way of getting the index of previous question? I know it’s mostly java question rather than Android but I think it could be useful to others as well.


#2

I can read your code and understand what it’s doing, so I think it’s perfectly fine.

Another programmer here used this solution, which I like:

mCurrentIndex = (mCurrentIndex + mQuestionBank.length - 1) % mQuestionBank.length;

The “%” is the modulo operator - it gives you the remainder when you divide by a number.


#3

Damn I’ve spent the last 30 mins trying to come up with that. Indexing by a modulus value is hard to wrap my head around :smiley:


#4

My way wasn’t nearly as elegant, but it works, and is easier to understand:

mCurrentIndex = (mCurrentIndex - 1);
if (mCurrentIndex < 0) mCurrentIndex = mQuestionBank.length - 1;


#5

Excellent! My app was crashing with an index out of bounds exception. Thanks, all!


#6

Since in Java when you calculate negative number modulus you will get also a negative number like:
-1 % 5 = -1
You might what to do this:
((-1 % 5) + 5) % 5 = 4

So following this alternative a previous question solution will be:
currentIndex = ((currentIndex - 1) % mQuestionBank.length) + mQuestionBank.length) % mQuestionBank.length;


#7

I guess mine was even less elegant. XD
if(mCurrentIndex==0){mCurrentIndex = mQuestionBank.length + (mCurrentIndex-1);}
else{mCurrentIndex -= 1 }