Previous Button Challenge


#1

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();
}

        }
    });

#2

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();

#3

Thank you for your help, I appreciate it.


#4

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


#5

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();
}
});


#6

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


#7

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.


#8

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.