I keep getting the “GeoQuiz has stopped” message everytime I try to click on the Prev Button (beeing at index = 0), so I never catch the last “question/answer” of the mQuestionBank array. Does anybody know the algorithm to loop arround the arrays values backwards? BTW here is my code:
Look like in your “if” statement that when the mCurrentIndex is already zero it would be go negative if you press the press the previous button. Seem like android doesn’t allow that so it crashes. To make it loop back maybe you could tell it to make mCurrentIndex to be the the number of questions total (mQuestionBank.length??) but only when you press the previous button and the index is already 0
Hello, I wrote this code and it worked, but I would like to know something, in the mNextButton listener, why do we get the modulus, ie.
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
I just can’t seem to figure it out, your help is highly appreciated.
mCurrentIndex += 1
if mCurrentIndex >= mQuestionBank.length {
// wrap around
mCurrentIndex = 0
}
This is because the expression n % M yields the remainder that results from dividing n by M. Since the remainder will always be less than M for positive integers M and n, it can be safely used index an array that contains M elements.
The remainder operator % is similar to the modulus operator.
Definition of modulo operation:
Let M be a positive integer (M > 0) and n be an integer,
then n can be written as the product of an integer k times M
plus a nonnegative integer r less then M.
n = k x M + r, where r >= 0 and r < M.
Then we say that n equals r modulo M.
n = r (modulo M)