当递增时,我怎么能让数组的索引“翻转”? [英] How could I have the index of an array 'roll over' when incrementing?

查看:175
本文介绍了当递增时,我怎么能让数组的索引“翻转”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个长度为4的数组。当我将它递增1并且数字大于数组的长度时,我希望它能翻转。

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.

例如:

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

我正在使用if-else来解决它这个

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.

编辑:我尝试了你的建议,但显然java的行为与负数表现奇怪。
当我尝试

Edit: I tried your suggestion, but apparently java behaves strangely with negative numbers. When I try

current_index = (current_index - 1) % textviewlist.length;

Java取索引0,将其减1( - 1)然后

Java takes the index "0", decreases it by 1 ("-1") and then

 -1 % 4 = -1

我预计它是3,见 Wolfram Alpha:-1 mod 4
但显然java%运算符不同于模运算符?

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?

编辑2 :我在这里找到了一个解决方案:使Java的模数表现得像它应该的最佳方法负数? - Stack Overflow

Edit 2: I found a solution here: Best way to make Java's modulus behave like it should with negative numbers? - Stack Overflow

我可以这么做:

current_index -= 1;
current_index = (current_index % textviewlist.length + textviewlist.length)  % textviewlist.length;


推荐答案

您可以使用模运算符。

current_index = (current_index + n) % 4;

这篇关于当递增时,我怎么能让数组的索引“翻转”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆