分配列表的上一个或下一个元素

assign the previous or next element of a list

public void nextElement() {
    //assign next element
    if (current != playlist.size() - 1)
        current++;
    else {
        current = 0;
    }
}

public void prevElement() {
    //assign previous element
    if (current == 0)
        current = playlist.size() -1;
    else {
        current--;
    }
}

我有一个简单的变量 current 并希望它在我调用这些方法时增加或减少,但是当 current = 1 并且我调用 prevElement() 时它被设置为 2 我只是不明白为什么,有人看到了吗它?卡普埃策

我已经为您的代码创建了相同的方法并迭代了多次,但没有发现任何错误。您可以在代码的某处嵌套或复杂调用这些方法吗?

    NEXTPrev np = new NEXTPrev();
    np.nextElement();
    np.prevElement();
    np.nextElement();
    np.nextElement();
    np.nextElement();
    np.nextElement();
    np.nextElement();
    np.prevElement();
    np.nextElement();
    np.nextElement();
    np.nextElement();
    np.nextElement();

    np.nextElement();
    np.nextElement();
    np.nextElement();
    np.nextElement();
    np.nextElement();
    np.nextElement();
    np.nextElement();
    np.nextElement();
    np.prevElement();


public class NEXTPrev {

    private int current = 0;

    private final ArrayList playlist;

    public NEXTPrev() {
        playlist = new ArrayList();
        populateArraylist();
    }

    public void populateArraylist() {
        playlist.add("a");
        playlist.add("a");
        playlist.add("a");
        playlist.add("a");
        playlist.add("a");
    }

    public void nextElement() {
        //assign next element
        if (current != playlist.size() - 1) {
            current++;
        } else {
            current = 0;
        }
        printCurr("n");
    }

    public void prevElement() {
        //assign previous element
        if (current == 0) {
            current = playlist.size() - 1;
        } else {
            current--;
        }
        printCurr("p");
    }


   public void printCurr(String str){
       System.out.println("Current. "+str+":" + current);
   }
}


the out put:
Current. n:1
Current. p:0
Current. n:1
Current. n:2
Current. n:3
Current. n:4
Current. n:0
Current. p:4
Current. n:0
Current. n:1
Current. n:2
Current. n:3
Current. n:4
Current. n:0
Current. n:1
Current. n:2
Current. n:3
Current. n:4
Current. n:0
Current. n:1
Current. p:0

n->next 和 p->previous 方法调用

也许您的代码中有错误而不是此处错误