简体   繁体   中英

Is is possible to make a cycling variable in Java?

I want to make a variable that can cycle around a specific value

Like if I set i to cycle from 0 to 7 and put i=5, then I add 2 to i it will be 7, I add 3 to i it will be 0, I add 4 to i it will be 1, and so on.

Is that possible?

You can't do it with primitives in an automated way, but you can use % :

(5 + 2) % 8 == 7
(5 + 3) % 8 == 0

If you were building a class, you could add addTo() or increment() methods that observe the bounds, but you'd lose some performance due to boxing.

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