C# 循环数组-从最后一个跳到第一个,反之亦然?

C# 循环数组-从最后一个跳到第一个,反之亦然?,c#,java,c++,C#,Java,C++,我有一个名为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

我有一个名为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

如果添加
消息,仍然可以使用单行余数技术。长度

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
公共类循环器{
静态int len=4;
静态int currentIndex=0;
公共静态void main(字符串[]args){
System.out.println(“Index=“+currentIndex”);
对于(int i=0;i<5;i++){
movePrev();
}
}//主要
公共静态void movePrev(){
currentIndex=(currentIndex+len-1)%len;
System.out.println(“移动的上一个索引=“+currentIndex”);
}
}//活套
输出:

索引=0
移动到上一个。索引=3
移动到上一个。索引=2
移动到上一个。索引=1
移动到上一个。索引=0
移动到上一个。指数=3


您真正想要的是模运算,而不是余数运算符()。这将具有处理负红利所需的语义。幸运的是,从另一个获得一个并不难:

public static int Modulus(int dividend, int divisor)
{
    return (dividend % divisor + dividend) % divisor;
}
你现在可以写:

int currentIndex = Modulus(currentIndex + 1, message.length);


@他想把它包起来around@AntP-如果currentIndex=0怎么办。然后,我们会有一种出界的感觉。我试图避免这种情况。
%
不是模运算符,而是余数运算符。如果它执行一个模数,它将按原样工作。预览!但是,这不是我想要的。请再看一遍这个问题。这可能是某种类型的作业,他受到if语句的限制。@DoubleDouble-事实上不是。在我的android书《大书呆子牧场指南》中,我看到了转到下一个的代码。想知道我是否可以为上一个做类似的事情。
是的,您可以在这里使用if-else检查,但我正在尝试避免。
这并不能避免…@Jarod42对,修复了。
int currentIndex = Modulus(currentIndex - 1, message.length);
//moveNext()

    if ( Length != 0 && ++currentIndex == Length ) currentIndex = 0;


//movePrevious

    if ( Length != 0 && currentIndex-- == 0 ) currentIndex = Length - 1;