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.
Diese Übung ist Teil des Kurses
Introduction to Testing in Java
Anleitung zur Übung
- Click "Run Code" to produce an
ArrayIndexOutOfBoundsExceptionand then submit.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
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;
}
}