2017-09-25 522 views
-1

我在這裏有一個代碼,它需要一個名爲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其中規定不好操作類型二元運算+之間的+標誌錯誤。如果你知道我能如何解決這個問題,請告訴我,我將非常感激。

+0

你應該使用向下轉換 – isaace

+0

什麼時候你的循環應該這樣做?你永遠不會改變'i'或'n',所以你的while循環將永遠重複。 – azurefrog

+0

另一種選擇是使用String'concat'方法而不是'+'運算符 – tommyO

回答

1

您可以更改

while (i < n){ 
    toRepeat = toRepeat + toRepeat; // operations are not defined for type Object 
} 
return toRepeat; 

String tr = (String)toRepeat; // cast to String 
while (i < n){ 
    tr = tr + tr; // valid on String 
    i++; // some condition to terminate 
} 
return tr; 

編輯:由於@oleg建議,使用StringBuilder要優於在循環連接字符串。


EDIT2:要一次增加一個字符,你可以這樣做:

String tr = (String)toRepeat; // this would be * 
String finalVal = ""; 
while (i < n){ 
    final = finalVal + tr; // would add * for each iteration 
    i++; 
} 
return finalVal; 
+1

是的,謝謝,似乎工作。 – CWilliams

+1

for循環可能更容易。 –

+0

**請勿使用!!! **這是一個** BIG **錯誤。不要在循環內連接字符串。每個循環迭代構建一個**新字符串**。結果在字符串池中,你得到了n個不同的字符串對象!如果你必須在循環中完成,那麼** StringBuilder **就是你的朋友。 –

1

這裏包括三個錯誤: 首先是toRepeatObject類型(並且它是final,即您可能不會分配新值):Object沒有+。您可以將其轉換爲String,如之前的答案所示。 第二:你的循環沒有終止,因爲i保持0。 第三:如果您增加i(例如循環中的i += 1)。第一次循環後您將獲得**,第二次循環後獲得****,第三次循環後獲得8星。

+0

所以我解決了其他問題,但我一個我怎麼能增加我只有1值 – CWilliams

+0

不要用字符串替換像tr + tr但串聯原始值:tr + torepeat。 – Stefan

0

我認爲Apache lib可以在大多數情況下提供幫助。它包含StringUtils類與許多有用的方法來使用String。這是其中之一:

public class RepeatIt { 
    public static String repeatString(final Object toRepeat, final int n) { 
     return toRepeat instanceof String ? org.apache.commons.lang3.StringUtils.repeat((String)toRepeat, n) : "Not a string"; 
    } 
} 
相關問題