Check if an array is sorted, return true or false

前端 未结 13 1973
隐瞒了意图╮
隐瞒了意图╮ 2020-11-30 06:03

I am writing an easy program the just returns true if an array is sorted else false and I keep getting an exception in eclipse and I just can\'t figure out why. I was wonder

13条回答
  •  -上瘾入骨i
    2020-11-30 06:44

    a[i+1] when i == a.length will give you that error.

    For example, in an array of length 10, you have elements 0 to 9.

    a[i+1] when i is 9, will show a[10], which is out of bounds.

    To fix:

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

    Also, your code does not check through the whole array, as soon as return is called, the checking-loop is terminated. You are simply checking the first value, and only the first value.

    AND, you have a semi-colon after your for loop declaration, which is also causing issues

提交回复
热议问题