2015-08-27 50 views
0
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指定列表中的前一个或下一个元素

+0

你确定傻冒调用'prevElement',而不是'nextElement'? – rzysia

+0

很确定,是的 – kapuetze

+0

调试应该有帮助 – rzysia

回答

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->未来和p>前面的方法调用

也许东西,而不是在你这里的代码是错误

+0

感谢您的测试,我会调试并再试一次 – kapuetze

+0

欢迎您 –

+0

如果有人会读这个,我意外地重置当前另一个方法,我打电话。两种方法都可以正常工作,因为burhancerit已经测试过了。 – kapuetze

相关问题