邊界情況:陣列最大值
另一個常見的程式練習是排序或找出陣列中的最大值。下面是它最簡單的版本,以及一個基本解法。這個解法並不完全正確,因為它沒有處理一個關鍵的邊界情況:空陣列,這會導致拋出例外。
執行程式碼來看看如何觸發 RuntimeException。
本練習屬於課程
Java 測試入門
練習說明
- 按下「Run Code」以產生
ArrayIndexOutOfBoundsException,然後送出。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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;
}
}