我應該撰寫一個遞回(!)方法來計算給定整數在整數陣列中的出現次數,如果偶數回傳真,奇數回傳假。到目前為止,這是我的代碼:
public static boolean evenNumberOf(int x, int[] arr) {
if (arr == null || arr.length == 0)
return false;
int count = counting(x, arr, 0, 0);
if (count % 2 == 0) {
System.out.print("true");
return true;
} else {
System.out.print("false");
return false;
}
}
public static int counting(int x, int[] arr, int index, int count) {
if (arr[index] == x && index < arr.length) {
return counting(x, arr, index , count );
} else {
return counting(x, arr, index , count);
}
}
它適用于
evenNumberOf(2, new int[] { 1, 2, 3, 2 });
但它給java.lang.StackOverflowError了
evenNumberOf(1, new int[] { 1, 2, 3, 2 });
我不確定如何防止這種無休止的遞回回圈,因為我是編程新手,這是我第一次使用遞回。提前致謝。
uj5u.com熱心網友回復:
任何遞回都應該有一個停止條件和 1 個或多個遞回呼叫。
在這個例子中,停止條件是index >= arr.length你開始撰寫函式如下:
public static int counting(int x, int[] arr, int index) {
if (index >= arr.length) {
return 0;//there are 0 x's between index and arr.length
}
處理完停止條件后,剩下的需要寫:
public static int counting(int x, int[] arr, int index) {
if (index >= arr.length) {
return 0;//there are 0 x's between index and arr.length
}
int countAfterIndex = counting(x, arr, index 1);//the amount of x's starting from index 1
if (x == arr[index]) {
return countAfterIndex 1;//there is 1 more to add
} else {
return countAfterIndex; //the amount of x's after index is the same as the amount from index.
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/371658.html
