Shrey
Shrey

Reputation: 532

Java – Unable to target an index in an integer array

Given an array full of integers, I need to print a sum that excludes the number 13 and also the number that comes immediately after 13, if there is any. For example:

int[] nums = {1, 1, 13, 1, 13} is supposed to return a sum of 2.

I looped through the array to exclude the 13's from the final sum, but I don't know how to target the index immediately after the index I'm trying to locate (if it exists). I keep running into "Array Index Out of Bounds Exceptions."

public static void main(String[] arguments) {

    int[] nums = {1, 1, 13, 1, 13};

    int targetNums = 0;
    int sum = 0;
    int sumFixed = 0;

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

    sumFixed = sum - targetNums;
    System.out.println(sumFixed);
}

Upvotes: 0

Views: 58

Answers (4)

Sebastian S
Sebastian S

Reputation: 4712

A different approach using an Iterator. So there is no need to deal with indexes or flags.

Iterator<Integer> iter = Arrays.asList(nums).iterator();
while (iter.hasNext()) {
    Integer num = iter.next();
    if (num == 13) {
        targetNums += num;
        if (iter.hasNext()) {
            targetNums += iter.next(); // not sure if you want to add this to targetNums, too...
        }
    } else {
        sum += num;
    }
}

Upvotes: 0

Kevin Seifert
Kevin Seifert

Reputation: 3572

public static void main(String[] arguments) {

    int[] nums = {1, 1, 13, 1, 13};

    int sum = 0;

    for (int i = 0; i < nums.length; i++) {
        if (nums[i] == 13) {
           i++; // skip current and next
        } else {
            sum += nums[i];
        }
    }

    System.out.println(sum);
}

Upvotes: 1

andrewdleach
andrewdleach

Reputation: 2466

public static void main(String[] arguments) {

int[] nums = {1, 1, 13, 1, 13};

int sumFixed = 0;
boolean foundThirteen = false;

for (int i = 0; i < nums.length; i++) {
    if (nums[i] == 13) {
        foundThirteen = true;
    } else if(!foundThirteen) {
        sumFixed = sumFixed + nums[i];
    }
}
System.out.println(sumFixed);
}

Upvotes: 0

rgettman
rgettman

Reputation: 178263

The code you have posted won't throw an ArrayIndexOutOfBoundsException. Perhaps you tried something else that did throw that exception. But it doesn't eliminate the number after the 13.

If the current number is 13, add the next number to targetNums, being careful not to go off the end of the array with a length check of the next index.

if (nums[i] == 13) {
    targetNums += nums[i];

    // Added code
    if (i < nums.length - 1)
    {
        targetNums += nums[i + 1];
    }
    // End added code
}

Upvotes: 4

Related Questions