[英]Error: bad operand types for binary operator '+'
我這里有一個代碼,它將一個名為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
之間的+
號上遇到錯誤,指出二進制運算符+
操作數類型錯誤。 如果您知道如何解決此問題,請告訴我,我將不勝感激。
你可以改變
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;
這里實際上存在三個錯誤:第一個是toRepeat
Object
類型(並且它是final
,即您可能沒有分配新的值):Object沒有+
。 您可以將其轉換為String
,如之前的答案所示。 第二:您的循環不會終止,因為i
保持為0
。 第三:如果增加i
(例如,循環中i += 1
)。 在第一個循環之后您將獲得**
,在第二個循環之后您將獲得****
,在第三個循環之后您將獲得8星。
我認為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";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.