2

I'm attempting to create a method that checks an array for increasing elements. True should be returned if all the elements are in increasing order. I get an out-of-bounds exception when I compare arr[i+1]. Any ideas on how I can make it work.

int[] one = {1,2,3,4,5};

public static boolean isIncreasing(int[]arr)
{
    boolean z = false;

    for(int i=0; i<arr.length;i++)
    {

        if(arr[i]<arr[i+1])
            {
                z = true;
            }
    }

    return z;
}
sbridges
  • 24,960
  • 4
  • 64
  • 71
jlss4e
  • 373
  • 3
  • 7
  • 11

5 Answers5

4

Because in a list with n items there are only n-1 gaps between them.

Change to

for (int i=0; i<arr.length-1; i++)

(Also you might want to check whether starting with false and setting to true is the right way around).

Owen
  • 38,836
  • 14
  • 95
  • 125
  • I tried to do that. The last element in the array doesn't get compared. If I change the last element to decreasing I still get "true". – jlss4e Aug 22 '11 at 04:23
4

You have two problems:

  1. Your loop is one iteration too long: Because you are checking element i+1, i needs to finished incrementing one iteration earlier than a usual loop.
  2. Your logic is flawed. Your loop will terminate the first time the check is true, so this array will pass: {1, 2, 0} when tested the first iteration tests 1 < 2 which is true, so return true - this is not what we want)

Fixing these two problems:

int[] one = {1,2,3,4,5};

public static boolean isIncreasing(int[] arr) {
    for(int i=0 ; i < arr.length - 1; i++) { // finish at length - 1
        if (arr[i] > arr[i+1]) {
            return false; // found elements that are out of order - return false
        }
    }    
    return true; // nothing out of order found - return true
}

This kind of logic - with an early exit with false on problem and a final return of true - is very common and a good pattern to learn.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
2

I suggest you write your method like this

public static boolean isIncreasing(int[]arr)
{
    for(int i=1; i<arr.length;i++)
    {
        if(arr[i-1]>arr[i])
            return false;
    }
    return true;
 }

it will help

  • return the proper result (yours returns true when it should not)
  • consider out of bounds
  • avoid unnecessary looping
Nicolas Modrzyk
  • 13,961
  • 2
  • 36
  • 40
1

You can use Java 8's IntStream.

import java.util.stream.IntStream;

public class Test {
  public static boolean isIncreasing(int[] a) {
    return IntStream.range(1, a.length).reduce(0, (acc, e) -> acc + (a[e - 1] <= a[e] ? 0 : 1)) == 0;
  }
}
wannik
  • 12,212
  • 11
  • 46
  • 58
1

You get that exception as when (i+1)'s value becomes array.length. For example if you have an array of length 10, the elements indexes will be from 0,1,2...till 9. so either you have to check till i < arr.length - 1 or you can modify your logic accordingly.

Swagatika
  • 3,376
  • 6
  • 30
  • 39