2017-03-01 30 views
0

我試圖讓此方法只運行兩次。我試圖通過一個計數器,像這樣的參數,但它似乎沒有工作。如何在2次迭代後停止此遞歸方法

@Override 
public IaaSService createCloudAndReturnWithIt(int counter, IaasService iaas) { 
    int counter = 0; 
    counter+=2; 
    try { 
     iaas = CloudLoader.loadNodes("C:\\Users\\Tom\\git\\dissect-cf-examp‌les\\PM.xml"); 
    } 
    catch (IOException | SAXException | ParserConfigurationException e) { 
     e.printStackTrace(); 
    } 
    return createCloudAndReturnWithIt(); 
} 
+2

傳遞一個計數器並遞增,直到達到所需的值 - 如果只執行兩次,則不會真正的似乎適合遞歸模式 –

+0

我試過傳遞一個計數器,它不起作用 –

+0

@SwitchCase告訴我們你已經試過 – Alexander

回答

1

在處理遞歸時,首先應該考慮的是如何退出遞歸循環。一旦你有辦法退出循環,你只需要調用自己的某種迭代。下面我所做的是在你的返回檢查中加入一個三進制數來檢查計數器是否小於或等於0.如果小於或等於0,我們返回iaas,否則我們返回一個調用相同的方法遞減計數器。在這個版本的循環中,它將從n次迭代,n是計數器。下面我說的重載版本的默認行爲:

public IaaSService createCloudAndReturnWithIt(int counter, IaasService iaas) 
{ 
    try 
    { 
     iaas = CloudLoader.loadNodes("C:\\Users\\Tom\\git\\dissect-cf-examp‌les\\PM.xml"); 
    } 
    catch (IOException | SAXException | ParserConfigurationException e) 
    { 
     e.printStackTrace(); 
    } 
    return (counter <= 0) ? iaas : createCloudAndReturnWithIt(--counter, iaas); 
} 

public IaaSService createCloudAndReturnWithIt(IaasService iaas) 
{ 
    return createCloudAndReturnWithIt(2, iaas); 
} 

Here是在Java中的遞歸一些文檔。如果您從未打算允許此用戶重複執行兩次以上的功能,請考慮根據您的使用情況將接受反向參數的方法設置爲private,package private或protected。

0

您所遇到的問題是,你永遠不要停止你的程序時,您的計數器命中2.另外,你把正在重置計數器每次的價值,所以也沒有取得任何進展。

爲了讓這個遞歸方法在兩次迭代之後停止,使用您試圖使用的計數器,您必須將計數器作爲參數傳遞,而不是每次都將其設置爲0,並且有條件檢查無論是否該停止遞歸。總之,它應該是這樣的:

public IaaSService createCloudAndReturnWithIt(int counter) { 
    //you would always run this with counter = 0 
    if(counter == 2){ 
     //return whatever IaaSService object you want this method to create 
    } 
    //Your other code to make whatever you need to happen happen. 
    counter++; 
    return createCloudAndReturnWithIt(counter);  
} 

這後兩個電話讓你的遞歸停止,但作爲用戶可怕袋熊在評論中指出的,如果你每次只遞歸兩次,它可能是更好的只是遍歷此代碼而不是使用遞歸。

而且,一般來說,當你使用遞歸,確保你有一個基本情況,否則遞歸將永遠不會結束,直到內存用完。

0

方法重載看起來像是解決問題的最佳方法。

// this should be the first method called 
@Override 
public IaaSService createCloudAndReturnWithIt(IaasService iaas) { 
    // the entry to the recursion, start the count at 0 
    return createCloudAndReturnWithIt(0, iaas); 
} 


// for improved efficiency this method should only be called by 
// this method so give it a private visibility 
// @Override <-- what are you overriding? 
private IaaSService createCloudAndReturnWithIt(int counter, IaasService iaas) { 
    try { 
     iaas = CloudLoader.loadNodes("C:\\Users\\Tom\\git\\dissect-cf-examp‌les\\PM.xml"); 
    } 

    catch (IOException | SAXException | ParserConfigurationException e) {  
    e.printStackTrace(); 
    } 

    // the key is to end the recursion with iaas after two iterations 
    return counter == 1 ? iaas : createCloudAndReturnWithIt(++count, iaas); 
}