Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

java - 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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the modulo operator.

current_index = (current_index + n) % 4;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...