Reputation: 590
I have this program, which does a whole heap of stuff but the part i'm having trouble with is summing the odd indexes in an arraylist.
Every 1, 3, 5, 7, etc. I need to sum and add to a variable. The variable is of datatype BigFraction
and the ArrayList - knowledge takes BigFractions only.
So originally I had
//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;
}
}
I'm really not sure if this is the right syntax for getting indexes of an Arraylist either... I guess you could use a .add or something too, but if anyone could shed light that would be awesome.
Cheers,
Sim
Upvotes: 0
Views: 1440
Reputation: 7804
Try this out :
// 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;
}
Upvotes: 2
Reputation: 500713
Here is a hint: you already know what the odd indices are. You've listed them in your question. All you have to do is find a way to loop over them.
Once you've figured that out, you'll need to find a way to get the element at the given index.
The rest, I am sure, will be easy.
Upvotes: 1