简体   繁体   English

如果在Java中会超过数组的0索引,该如何跳转?

[英]How to jump to 0 index of array if it will be exceeded in java?

Let's say that i have an array of int's in range 65-90. 假设我有一个介于65-90之间的int数组。 I'll randomly pick one of elements and add 10 to it. 我将随机选择一个元素,并添加10个元素。 Is it possible that value, if cross range of 90 return to 65? 如果交叉范围从90返回到65,该值是否可能? For example - i take a 85 and add 10 to it. 例如-我取85并加10。 So it should be 95, but i want a 70. 所以应该是95,但我要70。

You can do it by placing your value in the interval [0, high - low] by removing low to your value, then add the number you want to it, take the modulo of the sum, and finally add low back to get back in the range [low, high] 您可以通过以下方法来实现此目的:将值放置在[0, high - low]区间中[0, high - low]是将low删除,然后将所需的数字相加,取总和的模数,最后加low返回即可范围[low, high]

public static void main(String[] args) {
    int low = 65, high = 90;
    System.out.println(addWithinInterval(85, 10, low, high));
}

private static int addWithinInterval(int value, int add, int low, int high) {
    return (value - low + add) % (high - low + 1) + low;
}

I'll randomly pick one of elements and add 10 to it. 我将随机选择一个元素,并添加10个元素。 Is it possible that value, if cross range of 90 return to 65? 如果交叉范围从90返回到65,该值是否可能?

Sure, the remainder operator will do that for you: 当然,余数运算符将为您做到这一点:

n = (n - 65) % (90 - 65) + 65;

Example ( live copy ): 示例( 实时复制 ):

int n = 85;
for (int x = 0; x < 10; ++x) {
    n += 10;
    n = (n - 65) % (90 - 65) + 65;
    System.out.println(n);
}

Or here on site: Java and JavaScript are different, but their % operators work the same, so: 或网站上的此处:Java和JavaScript是不同的,但是它们的%运算符的工作原理相同,因此:

 let n = 85; for (let x = 0; x < 10; ++x) { n += 10; n = (n - 65) % (90 - 65) + 65; console.log(n); } 

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

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