我有一个名为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;
Run Code Online (Sandbox Code Playgroud)
要进入下一个元素 -
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.
}
Run Code Online (Sandbox Code Playgroud)
编辑 -
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
Run Code Online (Sandbox Code Playgroud)
如果添加message.length以下内容,您仍然可以使用单行余数技术:
int currentIndex = (currentIndex + message.length - 1) % message.length;
Run Code Online (Sandbox Code Playgroud)
它对索引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
Run Code Online (Sandbox Code Playgroud)
输出:
指数= 0已
移动上一个.指数= 3已
移动上一个.指数= 2已
移动上一个.指数= 1已
移动上一个.指数= 0已
移动上一个.指数= 3