'How calculate array integers sum array with index belongs to an interval in Java?

I'm trying to calculate the sum of the integers of array whose index belongs to the interval [n1; n2]

n1 & n2 are int & 0 <= n1 <= n2 < array.length

int[] array = new int[] {0, 1, 2, 3, 4, 5, 3}; 
int zeroToOne = calc(array,0, 1); // Should return 1
int zeroToFive = calc(array,0, 5); // Should return 15
int doubleZero = calc(array,0, 0); // Should return 0
int zeroToSix = calc(array, 0,6); // Should return 18

So I've tried three methods

First method:

public static int calc(int[] array, int n1, int n2) {

    int sum = 0;
    for (int i = 0; i < array.length; i++){
        if (i <= n2 && n1 <= i) {
            sum += i;
        }
    }
    return sum;
}

}

I got:

1 15 0 21

Second method:

public static int calc(int[] array, int n1, int n2) {

    int sum = 0;
    for (int a: array){
        if (n1 <= a && a <= n2){
            sum += a;
        }
    }
    return sum;
}

I got:

1 18 0 18

Third method:

public static int calc(int[] array, int n1, int n2) {
      
    return Arrays.stream(array, n1, n2).sum();
}

And I got:

0 10 0 15

How can I solve this problem?



Solution 1:[1]

A small change to your first function and it should work:

  public static int calc(int[] array, int n1, int n2) {

    int sum = 0;
    for (int i = n1; i <= n2; i++) {
      sum += array[i];
    }
    return sum;
  }

Note that we iterate over the elements from position n1 to n2, and summing them up.

Solution 2:[2]

The method you call:

Arrays.stream(array, n1, n2)

has the following definition in documentation:

stream(int[] array, int startInclusive, int endExclusive)

so you can see that the 3rd parameter is exclusive.

What you can do is just call it with the last index + 1. This should be fine:

return Arrays.stream(array, n1, n2+1).sum();

Solution 3:[3]

change first method to:

public static int calc(int[] array, int n1, int n2) {

    int sum = 0;
    for (int i = 0; i < array.length; i++){
        if (array[i] <= n2 && n1 <= array[i]) {
            sum += array[i];
        }
    }
    return sum;
}

and if you want to n1 & n2 are int & 0 <= n1 <= n2 < array.length,
you'd better check values of n1 and n2 and then if the condition was false do something like throw a exception

for do this:

public static int calc(int[] array, int n1, int n2) {
    if(!(n1>=0 && n1<=n2 && n1<=array.length && n2<=array.length)){
     // do something like throw a exception
    }
    int sum = 0;
    for (int i = 0; i < array.length; i++){
        if (array[i] <= n2 && n1 <= array[i]) {
            sum += array[i];
        }
    }
    return sum;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 idanz
Solution 2 Matt
Solution 3 MMR