2015-11-07 41 views
0

我試圖總計for循環中的分數。問題是for循環中的每個調用都使用回調函數。下面的代碼顯示了意圖,但我得到的錯誤是totalScore和totalHealth需要是最終才能使用。如果他們是最終的,那麼我不能總計他們。 java中沒有辦法做到這一點嗎?我意識到for循環將在不同的時間完成每個回調。爲了說明這一點,我運行自己的檢查時間(referencesAdded == totalReferences)來知道何時將分數和回調與答案相加。在使用回調(Java/Android)的for循環中累計值

我想基本的問題是:如何在使用回調的for循環中總計數字值?可能嗎?如果不是,我應該如何構造這種不同的結構?

public interface ScoreAndHealthCallback { 
    void scoreAndHealthReceivedCallback(Map<String, Number> scoreAndHealth); 
} 

public void scoreAndHealthForPassage(final Passage passage, final ScoreAndHealthCallback scoreAndHealthCallback) { 

    double totalScore = 0.0; 
    double totalHealth = 0.0; 

    int referencesAdded = 0; 
    int totalReferences = passage.references.size(); 

    for (Reference aReference : passage.references) { 

     scoreAndHealthForBaseLevelReference(aReference, new DataHelper.ScoreAndHealthCallback() { 

      @Override 
      public void scoreAndHealthReceivedCallback(Map<String, Number> scoreAndHealth) { 

       totalScore = totalScore + (double)scoreAndHealth.get("score"); 
       totalHealth = totalHealth + (double)scoreAndHealth.get("health"); 

       referencesAdded++; 

       if (referencesAdded == totalReferences) { 

        score = totalScore/counter; 
        health = totalHealth/healthPresentCounter; 

        Map<String, Number> map = new HashMap<String, Number>(); 
        map.put("score", score); 
        map.put("health", health); 
        scoreAndHealthCallback.scoreAndHealthReceivedCallback(map); 

       } 
      }; 

     }); 

    } 
} 

回答

0

沒有,因爲他們是按值引用傳遞到annonymous類的實例,而不是你不能改變那些局部變量(totalScore,...)。如果您確實需要與您所做的相似的行爲,則可以將這些局部變量包裝到本地類中,而不是使用它的實例。

看看這個例子,我提出:

package so; 

import java.util.Arrays; 

interface Work<T> { 

    void doWork(T item); 

} 

class CollectionUtils { 

    public static <T> void each(Iterable<T> iterable, Work<T> work) { 

     for (T item : iterable) { 

      work.doWork(item); 

     } 

    } 
} 

public class Example { 


    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     class Temp { 

      int total = 0; 

     }; 

     final Temp temp = new Temp(); 

     Integer[] values = {10, 20, 30}; 

     CollectionUtils.each(Arrays.asList(values), new Work<Integer>() { 

      public void doWork(Integer val) { 

       temp.total += val; 

      } 

     }); 

     System.out.println("Total value: " + temp.total); 

    } 

}