Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I have the index of an array 'roll over' when incrementing?

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;
like image 318
intagli Avatar asked Jul 26 '11 07:07

intagli


People also ask

How do you increment an index of an array?

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.

What does incrementing an array do?

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] ).

Which method is used to return the index of a selected element of an array in Java?

get() is an inbuilt method in Java and is used to return the element at a given index from the specified Array.


2 Answers

You can use the modulo operator.

current_index = (current_index + n) % 4;
like image 154
Karoly Horvath Avatar answered Sep 22 '22 18:09

Karoly Horvath


Divide the incremented index modulo the array's length:

current_index = (current_index + n) % textviewlist.length
like image 31
Xion Avatar answered Sep 24 '22 18:09

Xion