我應該編寫一個遞歸方法來刪除arrayList結尾的數字的重現。我覺得我已經覆蓋了所有可能出現的錯誤,但是第三次處理時出現了界限錯誤。我似乎無法弄清楚爲什麼我會遇到越界錯誤。好像我所有的計數都停留在正確的位置上,並且一旦計數器位置相等,我就有一個使用遞歸的if語句,這就是我認爲錯誤消息的地方。一些成功處理後遞歸方法出界錯誤
任何見解都會有幫助,需要從我的錯誤中學習。遞歸也不是我的強項。
編輯:這是列表; [100,200,200,300,400,300,100,500,500,400,100,400,100,100]
public static void deleteDuplicateValues(ArrayList<Integer> list, int decreasingCounter, int searchingVal, int outsideCounter)
{
int searchingValue = list.get(searchingVal);
if (outsideCounter < (list.size()-1))
{
if (searchingValue == list.get(list.size()-1-decreasingCounter)) //finds
{
System.out.print (searchingValue + " FOUND at position" + (list.size()-1-decreasingCounter) + "\n");
list.remove(list.size()-1-decreasingCounter);
deleteDuplicateValues(list, decreasingCounter,searchingVal+1, outsideCounter+1);
}
else
{
if (list.size()-1-decreasingCounter == outsideCounter) //gets to end without finding double
{//After searching x amount of times, they will equal eachother if not found.
//outsideCounter only increments when found or end of processing.
decreasingCounter = 0;
deleteDuplicateValues(list, decreasingCounter,searchingVal+1, outsideCounter+1); //goes to next position
}
else
{
System.out.print("executed");
deleteDuplicateValues(list, decreasingCounter+1, searchingVal, outsideCounter); //values UP1
}
}
}
這個功課/你是否需要使用遞歸? – turbo
是的不幸。循環會更容易。 – user90000000009
謝謝渦輪。非常有用的鏈接,但也很好奇爲什麼我的代碼無法正常工作。 – user90000000009