我在這裏有一個代碼,它需要一個名爲toRepeat
的字符串,並在同一行中重複n次。例如toRepeat = *,N = 3,結果= ***錯誤:二元運算符「+」的操作數類型錯誤
public class RepeatIt {
public static String repeatString(final Object toRepeat, final int n) {
int i = 0;
if (toRepeat instanceof String) {
while (i < n) {
toRepeat = toRepeat + toRepeat;
}
return toRepeat;
} else {
return "Not a string";
}
}
}
但是我得到了2 toRepeat
其中規定不好操作類型二元運算+
之間的+
標誌錯誤。如果你知道我能如何解決這個問題,請告訴我,我將非常感激。
你應該使用向下轉換 – isaace
什麼時候你的循環應該這樣做?你永遠不會改變'i'或'n',所以你的while循環將永遠重複。 – azurefrog
另一種選擇是使用String'concat'方法而不是'+'運算符 – tommyO