2016-03-03 86 views
2

我正在为Android创建一个音乐播放器,并且我正在尝试实现一个计时器功能,您可以在其中设置持续时间,并且该应用程序会为您提供具有此持续时间的播放列表。我试图用递归来做这件事很好。这里是我的代码:for循环的递归永不停止。找不到我的错误

变量:

maxLength = [any value in seconds] ... Wanted duration for the ArrayList with songs 
currentLength = 0 ... current Duration of the ArrayList 
timerSongs = new ArrayList<Song>() ... the ArrayList with the playlist 
allSongs ... ArrayList with all the songs I have on my device 

下面是被调用到项目添加到timerSongs

private void addSongs(int index, long maxLength){ 

    if (currentLength<=maxLength){ 
     timerSongs.add(allSongs.get(index)); 

     currentLength = currentLength 
      + TimeUnit.MILLISECONDS.toSeconds(allSongs.get(index).getDuration()); 

     for (int i = 0; i < allSongs.size() && currentLength != maxLength; i++){ 
      Log.e("Index", String.valueOf(i)); 
      addSongs(i, maxLength); 
     } 
    } else { 
     currentLength = currentLength 
      - TimeUnit.MILLISECONDS.toSeconds(timerSongs.get(timerSongs.size()-1).getDuration()); 
     timerSongs.remove(timerSongs.size()-1); 
    } 
} 

编辑无效:我试图做的是:

  1. 让应用添加歌曲到arrayList(timerSongs),直到它太长

  2. 删除过长的

  3. 添加下一首歌曲,然后再试一次,如果持续时间(currentLength)过长的歌曲。如果是的话,再次

  4. 删除它做步骤3,所有接下来的歌曲

  5. 如果持续时间仍是不正确的,树立了新的forelast歌,做上述再次

    等步骤上...

我找不到一个错误......但Log.e("Index", String.valueOf(i));总是给我相同的值:0。过了一段时间,因为一个堆栈溢出的应用程序崩溃。所以它似乎像递归永不停止。有人在我的代码中看到错误吗?有什么问题?

在此先感谢

+2

你为什么认为这将是递归很好的利用? –

+0

我不知道你在做什么,但这几乎肯定不是这样做的......但是因为我不知道你在做什么,所以我不能用更好的方式指出你的意思。 –

+0

因为节目首先必须添加歌曲,然后倒退并尝试所有组合以获得想要的结果。但是为什么我这么认为并不重要。我想帮助找到我的错误.. –

回答

0

我解决了我的问题。

如果有人有兴趣,这里是代码:

private void addSongs(int index, long maxLength){ 

     if (TimeUnit.MILLISECONDS.toSeconds(currentLength) <= maxLength){ 
      int i; 
      for (i = 0; i < songList.size() && TimeUnit.MILLISECONDS.toSeconds(currentLength) != maxLength; i++){ 
        timerSongs.add(songList.get(i)); 
        currentLength = currentLength + songList.get(i).getDuration(); 
        addSongs(i, maxLength); 
      } 
      if (i >= songList.size()){ 
       currentLength = currentLength - timerSongs.get(timerSongs.size()-1).getDuration(); 
       timerSongs.remove(timerSongs.size()-1); 
      } 
     } else { 
      currentLength = currentLength - timerSongs.get(timerSongs.size()-1).getDuration(); 
      timerSongs.remove(timerSongs.size()-1); 
     } 

} 
0

for循环将永远不会“++”,因为它等待addSongs方法执行完毕。当for循环与i == 0一起运行时,执行相同的方法会一次又一次地创建一个for循环,它始终有0作为我的基本int。这在逻辑上不会停止。尝试用这种替代for循环:

if(currentLength != maxLength){ 
    addSongs(index + 1, maxLength); 
} 
+0

当currentLength> maxLength时,递归调用将停止,并且命中'else', currentLength',然后返回到'i ++' –

0

好吧,虽然我个人认为您的解决方案使用递归一样,这是非常糟糕的,你应该改变这种线

for (int i = 0; i < allSongs.size() && currentLength != maxLength; i++){ 

for (int i = 0; i < allSongs.size() && currentLength <= maxLength; i++){ 
+0

'currentLength <= maxLength'已经在if语句中处理过了,所以只需要'i