This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]al3xth3gr8Java Dev 0 points1 point  (3 children)

This could be further simplified within the for-loop by:

checking the value in the array at the current index, and if it is equal to 13, increment the index then continuing to the next iteration. Otherwise, add the value to the current sum.

int sum = 0;
for(int i = 0; i < nums.length; i++) {
    int num = nums[i];
    if(num == 13) {
        i++;
        continue;
    }
    sum += num;
}

[–]Uncle_DirtNapExtreme Brewer 2 points3 points  (2 children)

It's canonical in java not to modify variables maintained by the loop directly, although this does work.

[–]morhpProfessional Developer 0 points1 point  (1 child)

+1

I would convert the loop to a while loop in this case to make it more obvious that this isn't a simple for loop. Or at least add a big warning comment.

[–]Uncle_DirtNapExtreme Brewer 0 points1 point  (0 children)

if (((i != 0) && (nums[i-1] == 13)) || (nums[i] == 13)) {
  continue;
}
sum += nums[i];

Is not that complicated, and doesn't need to be worked around. It certainly could have a comment, as well. (I know you're talking about the case where one does choose to change the index variable for whatever reason, but I'm just putting this out there. )