int*_*gli 5 java arrays indexing
所以我有一个长度为4的数组.当我将它递增1并且数字大于数组的长度时,我希望它能翻转.
例如:
current_index = 3;
current_index++;
//current_index is now 0 again
current_index = 3;
current_index += 2;
//current_index would be 1
current_index = 0;
current_index--;
//current_index would be 3
Run Code Online (Sandbox Code Playgroud)
我正在用if-else这样解决它
if (current_index == textviewlist.length + 1)
current_index = 0;
else if (current_index == textviewlist.length + 2)
current_index = 1;
else if (current_index == -1)
current_index = 3;
Run Code Online (Sandbox Code Playgroud)
但我觉得这不是一个合适的解决方案,或"好"的代码.
编辑:我尝试了你的建议,但显然java表现出奇怪的负数.当我尝试
current_index = (current_index - 1) % textviewlist.length;
Run Code Online (Sandbox Code Playgroud)
Java取索引"0",将其减1(" - 1")然后
-1 % 4 = -1
Run Code Online (Sandbox Code Playgroud)
我预计它会是3,见Wolfram Alpha:-1 mod 4 但显然java%运算符与模运算符不同?
编辑2:我在这里找到了一个解决方案:使Java模数表现得像负数的最佳方法是什么?- 堆栈溢出
我可以这样做:
current_index -= 1;
current_index = (current_index % textviewlist.length + textviewlist.length) % textviewlist.length;
Run Code Online (Sandbox Code Playgroud)
您可以使用模运算符.
current_index = (current_index + n) % 4;
Run Code Online (Sandbox Code Playgroud)
除以数组长度为模的增量索引:
current_index = (current_index + n) % textviewlist.length
Run Code Online (Sandbox Code Playgroud)