【发布时间】:2011-10-13 04:47:00
【问题描述】:
所以我有一个长度为 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
我目前正在用这样的 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;
但我觉得这不是一个合适的解决方案,也不是“好”的代码。
编辑:我尝试了您的建议,但显然 java 对负数的行为很奇怪。 当我尝试
current_index = (current_index - 1) % textviewlist.length;
Java 获取索引“0”,将其减 1(“-1”),然后
-1 % 4 = -1
我希望它是 3,请参阅 Wolfram Alpha: -1 mod 4 但显然java % 运算符与模运算符不一样?
编辑 2:我在这里找到了解决方案:Best way to make Java's modulus behave like it should with negative numbers? - Stack Overflow
我只能这样做:
current_index -= 1;
current_index = (current_index % textviewlist.length + textviewlist.length) % textviewlist.length;
【问题讨论】: