These approaches are provided based on your implied requirement that you must explicitly multiply each pair of elements and take their sum. There are other ways to achieve the sum that are more effiicent.
You need a nested loop.
- the outer loop starts at
i = 0
.
- the inner loop starts a
k = i+1 = 1
.
- this ensures the sum doesn't include the square of each entry.
List<Integer> nums = List.of(1,3,5,7);
int sum = 0;
for (int i = 0; i < nums.size(); i++) {
for (int k = i+1; k < nums.size(); k++) {
sum += nums.get(i)*nums.get(k);
}
}
System.out.println(sum);
Prints
86
You could also do it like this using an enhanced for loop as the outer loop. But the first method is, imo, more straight forward.
int sum = 0;
int i = 1;
for (int v : nums) {
for (int k = i++; k < nums.size(); k++) {
sum += v*nums.get(k);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…