mercredi 24 juillet 2019

If statement greater than operation don't work

when write the statement to tell the program to break or return, the if statement still executes every time when the condition is not satisfied and cause error :java.lang.ArrayIndexOutOfBoundsException

I've tried greater than and equal ==, both worked. And I checked ">" is also an operator in java. Then why it still executes?

public class adjacentElementsProduct {

    static int adjacentElementsProduct(int[] inputArray) {
    if(inputArray ==null|| inputArray.length<0) return 0;
    int res=Integer.MIN_VALUE;

    for( int i=0; i<inputArray.length;i++){
       int stop=i+1;

       if((i+1) > inputArray.length) break;

       res=Math.max(res,inputArray[i]*inputArray[i+1]);
    }
    return res;
}

'''

In this case, since '''if((i+1) > inputArray.length) break;''' doesn't work, so the error message is: java.lang.ArrayIndexOutOfBoundsException

Aucun commentaire:

Enregistrer un commentaire