Edge cases: Array maximum
Another common programming exercise is about sorting or finding the maximum value in an array. Here is the simplest version of a it, together with a basic solution. The solution is not entirely correct, as it does not handle a key edge case, an empty array, which will result in an exception.
Run the code to see a RuntimeException
triggered.
Este exercício faz parte do curso
Introduction to Testing in Java
Instruções do exercício
- Click "Run Code" to produce an
ArrayIndexOutOfBoundsException
and then submit.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
public class MaxValue {
public static void main(String[] arguments) {
// Enter the array elements that cause an ArrayIndexOutOfBoundsException
System.out.println(findMax(new int[]{}));
}
public static int findMax(int[] numbers) {
int max = numbers[0];
for (int num : numbers) {
if (num > max) {
max = num;
}
}
return max;
}
}