求和数组元素的奇数索引

时间:2013-03-25 08:06:17

标签: java arraylist

我有这个程序,它完成了一大堆东西但是我遇到麻烦的部分是在一个arraylist中对奇数索引求和。

每1,3,5,7等我需要求和并添加到变量中。变量的数据类型为BigFraction ArrayList - 知识仅采用BigFractions

所以最初我有

 //Returns the combined probability (the odd indexes of the arraylist)
public BigFraction weight() {
    BigFraction sum;
    if (knowledge.indexOf(knowledge)%2 == 1)
        sum+ = no idea what to put in here
        return sum;
    }
}

我真的不确定这是否是获取Arraylist的索引的正确语法...我猜你也可以使用.add或者其他东西,但是如果有人可以发光那将是非常棒的。

干杯,

2 个答案:

答案 0 :(得分:2)

试试这个:

// Returns the combined probability (the odd indexes of the arraylist)
public BigFraction weight() {
    BigFraction sum;
    for (int index = 1; index < knowledge.size(); index = index + 2) {
        sum = sum.add(knowledge.get(index));
    }

    System.out.println("Sum is  " + sum);

    return sum;
}

答案 1 :(得分:1)

这是一个提示:你已经知道奇数指数是什么。你已经在问题中列出了它们。您所要做的就是找到一种方法循环

一旦你想到这一点,你就需要找到一种方法获取给定索引的元素。

其他,我相信,很容易。

相关问题