简体   繁体   中英

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.

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

(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.

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

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. Quoting its Javadoc (emphasis mine):

The floor modulus is x - (floorDiv(x, y) * y) , has the same sign as the divisor y , and is in the range of -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 .

index = arraySize - ((index + 1) % arrySize)

Use this if you want 1-based indexing. For example if you wanted to step backwards through months where 1 is January.

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

Example Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM