Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Java) Check array for increasing elements

Tags:

java

arrays

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;
}
like image 484
jlss4e Avatar asked Jul 10 '26 09:07

jlss4e


1 Answers

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).

like image 168
Owen Avatar answered Jul 14 '26 02:07

Owen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!