I would like to write a program which adds up all the numbers in an integer array - with an exception! Since the number 6 isn't the nicest, I propose that we exclude all sections of numbers beginning with a 6 and ending with a 7 - inclusive. Every 6 will always be followed by a 7, but not necessarily vice versa.
Here are a few examples of the input arrays and their expected output:
sum67([1, 2, 2, 6, 99, 99, 7]) = 5
All numbers between a 6 and a 7 are excluded.
sum67([1, 2, 2]) = 5
No 6's or 7's here.
sum67([1, 1, 6, 7, 2]) → 4
Neither the 6 or the 7 is included.
All the above tests passed.
Once again, the method header is fixed, and I may only change the body of the method. Here is my attempt at the code:
public int sum67(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length; i++) {
// Adding all numbers that are not a 6
if (nums[i] != 6) sum += nums[i];
}
for (int j = 0; j < nums.length; j++) {
// check for the sixes - the lower bound exclusive
if (nums[j] == 6) {
for (int k = j + 1; k < nums.length; k++) {
// check for the sevens - the upper bound inclusive
if (nums[k] == 7) {
// take away all the numbers between the 2 bounds, including the 7
for (int m = j + 1; m <= k; m++) {
sum -= nums[m];
}
}
}
}
}
return sum;
}
The above program not only does not work, but is clearly extremely messy. In particular, it fails the following tests, among others:
sum67([1, 6, 2, 6, 2, 7, 1, 6, 99, 99, 7]) = 2
Actual output is -463
!
sum67([2, 2, 6, 7, 7]) = 11
Actual output is -3
.
So essentially:
Where is the error line or lines in my code?
Is there a better way of writing this program that doesn't have as many loops and nested if
s?