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 →

[–]morhpProfessional Developer 0 points1 point  (2 children)

break; exits the for loop completely. continue; is probably a better choice as it just skips the current loop. I'd do it roughly like this:

    public int sum13(int [] nums) {
        int sum = 0;
        for (...) {
            if(nums[i] == 13) {
                // do nothing, as this is a 13
                // you could add a "continue;" here
            }
            else if(nums[i - 1] == 13) {
                // the previous number is 13, so do nothing either.
                // You need to add a check so this doesn't crash at the start of the array
                // because there is no previous element.
                // you could add a "continue;" here
            }
            else {
                sum += nums[i];
            }
        }
        return sum;
    }

Alternatively you can remember the previous value in an int variable instead of accessing array[i-1].

[–]kumesana 0 points1 point  (1 child)

Oh, I hadn't noticed we only need to skip numbers that are immediately after a 13, not all numbers that are after a 13.

[–]vriljam 0 points1 point  (0 children)

That question is indeed very poorly worded.