简体   繁体   English

可以在Java中制作循环变量吗?

[英]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. 就像如果我将i设置为从0到7循环并放置i = 5,那么我将2加到i等于7,将3加到i等于0,将4加到i等于1,所以上。

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. 如果要构建类,则可以添加遵守边界的addTo()increment()方法,但是由于装箱而导致的性能addTo()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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