[英]How can I increment and decrement an integer with the modulo operator
I am trying to increment an integer based on a click.我正在尝试根据点击增加一个整数。 How the click happens does not matter so I'll stick to the logic.点击如何发生并不重要,所以我会坚持逻辑。 I am doing this in Java but the logic should be the same all around.我在 Java 中这样做,但逻辑应该是一样的。
int index = 0;
// then within the click event
//arrySize holds the size() of an ArrayList which is 10
index = (index + 1) % arrySize;
With this logic, every time the user clicks, index
will increment by 1. Then its modulo of arrySize
causes index
to go back to 0 when index
matches arrySize
有了这个逻辑,每次用户点击, index
都会增加1。然后它对arrySize
的模导致index
在index
匹配arrySize
时回到0
(10 % 10 would make the index go back to 0) Which is great because it's kind of like a loop that goes from 0 to 10 then back to 0 and never over 10. (10 % 10 会使索引回到 0)这很好,因为它有点像从 0 到 10 然后回到 0 并且永远不会超过 10 的循环。
I am trying to do the same logic but backwards where based on the click the number will decrement and get to 0 then goes back to the arrySize
instead of -1
我正在尝试执行相同的逻辑但是向后,根据点击数字将递减并达到 0 然后返回到arrySize
而不是-1
How can I achieve this logic?我怎样才能实现这个逻辑?
(index + arraySize - 1) % arraySize
Does what you want.做你想做的事。
Starting with Java 8, you can use the Math.floorMod(x, y)
method.从 Java 8 开始,您可以使用Math.floorMod(x, y)
方法。 Quoting its Javadoc (emphasis mine):引用其 Javadoc(强调我的):
The floor modulus is
x - (floorDiv(x, y) * y)
, has the same sign as the divisory
, and is in the range of-abs(y) < r < +abs(y)
. floor 模数是x - (floorDiv(x, y) * y)
,与除数y
具有相同的符号,并且在-abs(y) < r < +abs(y)
的范围内。
System.out.println(Math.floorMod(-1, 5)); // prints 4
So you will have:所以你将拥有:
index = Math.floorMod(index - 1, arrySize);
You can't have directly -1 % 5
because that will output -1
based on how the operator %
operates with negatives numbers .您不能直接使用-1 % 5
,因为这将根据运算符%
对负数的运算方式输出-1
。
index = arraySize - ((index + 1) % arrySize) index = arraySize - ((index + 1) % arrySize)
Use this if you want 1-based indexing.如果您想要基于 1 的索引,请使用此选项。 For example if you wanted to step backwards through months where 1 is January.例如,如果您想倒退到 1 是一月的月份。
int previous = ((index - 1 - arraySize) % arraySize) + arraySize
Results结果
index previous
1 12
2 1
3 2
4 3
5 4
6 5
7 6
8 7
9 8
10 9
11 10
12 11
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.