2016-03-03 89 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