在使用回调的for循环中累计值(Java / Android)

时间:2015-11-07 21:50:34

标签: java android android-studio

我试图在for循环中累计得分。问题是for循环中的每个调用都使用回调。以下代码显示了意图,但我得到的错误是totalScore和totalHealth需要最终才能使用。如果他们是最终的那么我就无法完成它们。 java中没有办法让这种情况发生吗?我意识到for循环将在不同的时间完成每个回调。为了解释这个问题,我自己检查何时(referencesAdded == totalReferences)来知道何时将答案加起来并回答答案。

我想基本的问题是:如何在使用回调的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);

                }
            };

        });

    }
}

1 个答案:

答案 0 :(得分:0)

不,您无法更改这些局部变量(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);

    }

}
相关问题