Previous Button Challenge

Hi,

mPreviousButton = (Button) findViewById(R.id.previous_button);
mPreviousButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
if (mCurrentIndex == 0) {
updateQuestion();
}else {
mCurrentIndex = (mCurrentIndex -1 ) % mQuestionsBank.length;
updateQuestion();
}

        }
    });

Hi!, I’m Chinese student. Maybe my English is poor,but I want to help you.
This is my code

if(mCurrentIndex == 0)
 {
        mCurrentIndex= mQuestionBank.length - 1;
  }
   else
    mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;

  updateQuestion();
4 Likes

Thank you for your help, I appreciate it.

another example of a solution:
mCurrentIndex = (mQuestionBank.length + mCurrentIndex - 1) %mQuestionBank.length;
updateQuestion();

1 Like

hi,I’m Chinese student. Maybe my English is poor,but I want to help you.And I have a another idea.
mPrevButton = (Button) findViewById(R.id.prev_button);
mPrevButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view){
mCurrentIndex = (mCurrentIndex + 4) % mQuestionBank.length;
updateQuestion();
}
});

I choose to +4 .As you can see, the code is short,but it can work well.

Great solution!

For anyone confused, the issue with this code:

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

is that if mCurrentIndex starts out as 0 the value in the parenthesis go to -1 and then the mod calculation throws an error and ends the program.

I also like this solution. It is essentially the same as marfars but is better because it allows you to also change the size of the array of questions.

hi
I have a question for this part…Why we just use to (mCurrentIndex +1)??
why we must to use this mQuestionBank.length?

Excellent solution. I love short code.
P.S. Sorry for my english.

Should be the accepted answer as it work for every case unlike

(mCurrentIndex + 4) % mQuestionBank.length; and

 `if(mCurrentIndex == 0)
 {
        mCurrentIndex= mQuestionBank.length - 1;
  }`

which will only fetch the last Question every time. Cheers to John_Doe.