這一直讓我頭痛,我無法弄清楚。目標是讓字符串重複使用時間參數作爲字符串能夠重複其自身的次數。 例如:使用遞歸連接字符串
stringTimes("Hello", 3); //should return HelloHelloHello,
stringTimes("cat", 2); //should return catcat,
stringTimes("monkey", 0); //should return _____,
下面
是我一直使用的代碼,我得到什麼。 幫助!
public static String stringTimes(String theString, int times)
{
String adder = "";
if (times >= 1) {
adder += theString;
return stringTimes(theString, times - 1);
}
return adder;
}
public static void main(String[] args) {
System.out.println(stringTimes("hello ", 8));
}
您需要將「加法器」傳遞給stringTimes的內部調用(而不是原始字符串,theString) – FishStix
如果這是一個類分配,它是一個非常糟糕的。遞歸是這項工作的錯誤工具。如果你在教汽車修理課,你會要求學生用一把小鉗子擰緊螺母,「就像練習一樣」? –
是的,但後來又有一項任務要求我使用for循環 –