So let's say I have an array of length 5 (let's just call it myArray[5]). If I add 4 to myArray[3], such like myArray[3+4], how can I make it loop through myArray again so that it becomes myArray[2]?
example)
myArray[3]
myArray[4] //+1
myArray[0] //+2
myArray[1] //+3
myArray[2] //+4
Just use the array length for a modulo operation:
int index = /* index you are using */;
myArray[index % myArray.length]
You can use modulus. index % myArray.length like
int[] myArray = new int[10];
for (int i = 10; i < 20; i++) {
System.out.println(i % myArray.length);
}
Output is 0 - 9 (inclusive).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With