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

时间:2015-08-27 11:38:39

标签: next

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 = 1并且我调用prevElement()时它被设置为2并且我根本不明白为什么,有人看到它吗? Kapuetze

1 个答案:

答案 0 :(得分:0)

我创建了相同的代码方法,并多次迭代,没有看到任何错误。您可以在代码中的某个位置对这些方法进行嵌套或复杂调用。

    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->以前的方法调用

也许你的代码中的某些东西不是错误的