我有一个名为message的数组。当用户输入“下一个”时,我移动到下一个索引。同样,对于以前。我希望能够以一种简单的方式转移到下一个和上一个。 我知道下一个但不是之前的简单方法。我该怎么做?
array[] message = {"Hello", "good", "people", "!"};//index starts at 0
int currentIndex = 0;
int next = 2;//an option which can be used in an if or switch-case
int previous = 1;
转到下一个元素 -
moveNext(){
int currentIndex = (currentIndex + 1) % message.length;
}
//Any neat trick, similar to the one for moveNext() ?
movePrevious(){
//Yes, you can use an if-else check here, but I am trying to avoid that.
}
修改
Example - Array is of LENGTH = 5, that is indexes 0 to 4.
When currentIndex = 4 and you enter next, then set currentIndex = 0
When currentIndex = 0 and you enter previous, then set currentIndex = 4
答案 0 :(得分:8)
如果添加message.length
:
int currentIndex = (currentIndex + message.length - 1) % message.length;
它对索引0更有帮助,但它似乎是你正在寻找的。请注意添加会引起长度溢出的可能性。
显示逻辑的示例代码:
public class Looper {
static int len = 4;
static int currentIndex = 0;
public static void main(String[] args) {
System.out.println("Index = " + currentIndex);
for(int i = 0; i < 5; i++){
movePrev();
}
}// main
public static void movePrev(){
currentIndex = (currentIndex + len - 1) % len;
System.out.println("Moved prev. Index = " + currentIndex);
}
}// Looper
输出:
指数= 0
移动了上一个。指数= 3
移动了上一个。指数= 2
移动了上一个。指数= 1
移动了上一个。指数= 0
移动了上一个。指数= 3
答案 1 :(得分:2)
你真正想要的是模数运算,而不是余数运算符(What's the difference?)。这将具有处理负红利所需的语义。幸运的是,从另一个中获取一个并不太难:
public static int Modulus(int dividend, int divisor)
{
return (dividend % divisor + dividend) % divisor;
}
您现在可以写:
int currentIndex = Modulus(currentIndex + 1, message.length);
或
int currentIndex = Modulus(currentIndex - 1, message.length);
答案 2 :(得分:1)
//moveNext()
if ( Length != 0 && ++currentIndex == Length ) currentIndex = 0;
//movePrevious
if ( Length != 0 && currentIndex-- == 0 ) currentIndex = Length - 1;