2012-09-23 56 views
2

我被要求編寫遞歸方法來反轉字符串。我有一個名爲Sentence的類,它帶有一個名爲text的私有字符串變量。通過創建Sentence對象和調用方法,程序在單獨的主類中運行。我不能改變方法的返回類型。我一直在研究這一點,並且一無所獲。任何幫助或建議,將不勝感激。使用遞歸進行字符串反轉w o參數

public void reverse() { 
    if (text.length() <= 1) { 
     return; 
    } 

    Sentence x = new Sentence(text.substring(1)); 
    recur = text.substring(0, 1); //recur is another String variable I declared 
    text = x.text.concat(recur); 
    x.reverse(); 
} 
+1

你知道「遞歸」是什麼意思嗎?忘記它,對不起。我完全讀錯了代碼。 – Fildor

+0

@Fildor你有什麼意見?該代碼片段是遞歸的。它甚至可以正確終止! – verdesmarald

+0

是的,我知道。算了吧。我在代碼中理解錯誤。但現在我意識到了。恥辱在我:) – Fildor

回答

3

你很近。至於我可以看到這個應該工作,如果你換兩行:

text = x.text.concat(recur); 
x.reverse(); 

此外,你應該儘量想出有意義的變量名稱,而不是xrecur。這會讓其他人(和你!)更容易理解你的代碼。例如:

public void reverse() { 
    if (text.length() <= 1) 
     return; 

    String firstChar = text.substring(0, 1); 

    Sentence rest = new Sentence(text.substring(1)); 
    rest.reverse(); 

    text = rest.text.concat(firstChar); 
}