(Java) Check array for increasing elements

前端 未结 5 1683
旧时难觅i
旧时难觅i 2021-01-03 13:48

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

5条回答
  •  伪装坚强ぢ
    2021-01-03 14:18

    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.

提交回复
热议问题