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

Java mCurrentIndex=(mCurrentIndex+;1)%mQuestionBank.length;,java,android,arrays,modulo,Java,Android,Arrays,Modulo,我不理解以下语法: mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length; (mQuestionBank是一个数组) %mQuestionBank.length的原因是什么?%是mod运算符。此运算符将%前面的值除以%后面的值后,得到余数 比如说, 5 % 2 = 1 这是因为当你将5除以2时,你会得到1的余数。它在逻辑上等价于 if (mCurrentIndex + 1 < mQuestionBank.length) {

我不理解以下语法:

mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
mQuestionBank
是一个数组)


%mQuestionBank.length
的原因是什么?

%
是mod运算符。此运算符将
%
前面的值除以
%
后面的值后,得到余数

比如说,

5 % 2 = 1

这是因为当你将5除以2时,你会得到1的余数。

它在逻辑上等价于

if (mCurrentIndex + 1 < mQuestionBank.length) {
    mCurrentIndex++;
} else {
    mCurrentIndex = 0;
}
if(mCurrentIndex+1

用于在数组中旋转索引而不超过其边界。

以循环方式访问数组的元素


mCurrentIndex
将始终绑定在范围[0,
array.length

是的,这是基本的mod逻辑

基本上,如果你有一个问题数量有限的测验,你将与国防部一次又一次地循环测验

例如,假设您有一个包含4个问题的数组

它将是: [0,1,2,3]

既然你有 mCurrentIndex=(mCurrentIndex+1)%mQuestionBank.length

0%4 = 0 hence index 0, so it returns the question on index 0. 
1%4 = 1 hence index 1, so it returns the question on index 1. 
2%4 = 2
3%4 = 3
4%4 = 0
因此,它永远不会提供超过3的索引


该应用程序将继续在一个循环中问相同的4个问题。如果你有更多的问题,那么它会问更多。

如果(++mCurrentIndex==mQuestionBank.length){mCurrentIndex=0;}
,那么说
会更短。不过,我还是投了赞成票。
503%4 = 3
504%4 = 0