I'm learning Java and I trying to construct a method for my homework. It takes as argument an Array and returns the difference between its elements (as absolute value).
For example: array {7,8,5,7,2}
the difference between elements 0 and 1 is 1 (=7−8)
the difference between elements 1 and 2 is 3 (=8−5)
the difference between elements 2 and 3 is 2 (=5-7)
the difference between elements 3 and 4 is 5 (=7−2)
the difference between elements 4 and 0 is 5 (=2-7)
If there are multiple candidates the method will return the one with the greatest index. In this example, the last one. If the array is empty, then the method must return −1.
I have some problems in my code (as you can see) and the biggest one is that my method returns only the last diff and not the biggest one with the higher index. Can someone help me? I'm not figuring out how to solve this problem.
public static int MaxDiff(int[] array){
int diff = 0;
if (array.length == 0){ // Checks for empty array
return -1;
}
for (int i = 0; i <= array.length; ++i){
if(i == array.length){
diff = Math.abs(array[i] - array[0]);
} else {
diff = Math.abs(array[i] - array[i+1]); // Mistake. Can be
// bigger than array
}
}
return diff;
}
ArrayIndexOutOfBoundExceptionifinside the loop to check, if it's the last iteration. Just add the code after the loop instead.