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