So I have an Array with a length of 4. When I increment it by 1 and the number gets bigger than the length of the array, I'd like it to rollover.
For example:
current_index = 3;
current_index++;
//current_index is now 0 again
current_index = 3;
current_index += 2;
//current_index would be 1
current_index = 0;
current_index--;
//current_index would be 3
I'm currently solving it with if-else like this
if (current_index == textviewlist.length + 1)
current_index = 0;
else if (current_index == textviewlist.length + 2)
current_index = 1;
else if (current_index == -1)
current_index = 3;
But I feel like this isn't an appropriate solution, or "good" code.
Edit: I tried your suggestion, but apparently java behaves strangely with negative numbers. When I try
current_index = (current_index - 1) % textviewlist.length;
Java takes the index "0", decreases it by 1 ("-1") and then
-1 % 4 = -1
I expected it to be 3, see Wolfram Alpha: -1 mod 4 But apparently the java % operator is not the same as the modulo operator?
Edit 2: I found a solution here: Best way to make Java's modulus behave like it should with negative numbers? - Stack Overflow
I can just do:
current_index -= 1;
current_index = (current_index % textviewlist.length + textviewlist.length) % textviewlist.length;
To increment a value in an array, you can use the addition assignment (+=) operator, e.g. arr[0] += 1 . The operator adds the value of the right operand to the array element at the specific index and assigns the result to the element.
Here the Array[i]++ increments the value of the element array[i] , but array[i++] increments the i value which effects or changes the indication of the array element (i.e. it indicates the next element of an array after array[i] ).
get() is an inbuilt method in Java and is used to return the element at a given index from the specified Array.
You can use the modulo operator.
current_index = (current_index + n) % 4;
Divide the incremented index modulo the array's length:
current_index = (current_index + n) % textviewlist.length
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