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);
}
};
});
}
}