0

I am trying to add all numbers in an array that are more than the last number it checked. I am getting this error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at RaySumLast.sum(RaySumLast.java:16)
    at RaySumLast.main(RaySumLast.java:25)

Here is my code:

class RaySumLast
{
    static int arr[] = {-99, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5};

    static int sum()
    {
        int sum = 0;

        for (int i : arr) {
            if (i < arr[i-1])
                sum += i;
        }
        return sum;
    }

    public static void main(String[] args)
    {
        cSystem.out.println(sum());
    }
}

How can I fix this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
David B
  • 11
  • 5
  • 2
    Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Scratte Feb 21 '20 at 22:16
  • When `j` is `0`, then `j-1` is `-1`. That's not a valid index for any array. – Scratte Feb 21 '20 at 22:18
  • I see you updated your code. Now in the first run of your loop `i = -99` and you'll be trying to find the `-100th` element in the array. – Scratte Feb 21 '20 at 22:23
  • i contains the value of the array at index i. The first value of the array is -99. When you check the value of a[i - 1] you are trying to access the value at -100. – NomadMaker Feb 21 '20 at 23:51
  • 1
    What do/don't you understand from that error? – AMC Feb 22 '20 at 01:20

4 Answers4

3

You can't use the value in your array as an index into your array. Even if you skip the initial value of the array, it will fail as soon as there's a value that exceeds the bounds, as in this example (notice the 20):

static int arr[] = {-99,1,2,3,4,5,6,7,8,9,20,5};

If you want to use the enhanced for loop, you can use this:

int prev = arr[0];
int sum = prev;

for (int i : arr) {
  if (i > prev)
    sum += i;
  prev = i;
}

However, I much prefer to use the answer by @Domin0 that loops over the indexes.

Scratte
  • 3,056
  • 6
  • 19
  • 26
1
class RaySumLast 
{ 
   static int arr[] = {-99,1,2,3,4,5,6,7,8,9,10,5}; 

   static int sum() 
   { 
      int sum = arr[0];
      for (int i=1; i<arr.length; ++i) {
         if (arr[i] > arr[i-1])
            sum += arr[i];
      }
      return sum; 
   } 
   public static void main(String[] args)  
   { 
      System.out.println(sum()); 
   } 
}

This solution assumes the array is not empty and that the 1st element should always be part of the sum.

Domin0
  • 197
  • 2
  • 11
0

This may help you:


class RaySumLast
{
    static int arr[] = {-99,1,2,3,4,5,6,7,8,9,10,5};

    static int sum()
    {
        int sum = 0;
        int index = 0;
        for (int i : arr) {
            if(index == 0) sum += i;
            else {
                if (i > arr[i-1])
                    sum += i;
            }
            index ++;

        }
        return sum;
    }
    public static void main(String[] args)
    {
        System.out.println(sum());
    }
}


Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
YouXiang-Wang
  • 1,119
  • 6
  • 15
0

I had to make some assumptions.

  1. The first number will always be included in the sum.
  2. All numbers will be checked. So all the 5's in the sequence (10, 5, 10, 5, 10, 5, 10) would be skipped and the sum would be 40.
  3. I also think it would be better style to supply the array as an argument. It also makes it easier to test different cases.
    public static int sum(int[] arr) {
        int sum = 0;
        // set the last to the smallest possible integer.
        int last = Integer.MIN_VALUE;
        for (int n : arr) {
            if (n > last) {
                // sum if current value is > than last.
                sum += n;
            }
            // always update last to current value.
            last = n;
        }
        return sum;
    }

Here is a somewhat different approach by using streams. Same assumptions as before. The indices start at 1 and go to arr.length -1 Thus the first array element must be added to the final sum.

public static int sum(int[] arr) {
    return arr[0] + IntStream.range(1, arr.length)
            .filter(i -> arr[i] > arr[i - 1])
            .map(i -> arr[i]).sum();
}
WJS
  • 36,363
  • 4
  • 24
  • 39