错误:二元运算符“+”的操作数类型错误
我在这里有一个代码,它需要一个名为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;
是的,谢谢,似乎工作。 – CWilliams
for循环可能更容易。 –
**请勿使用!!! **这是一个** BIG **错误。不要在循环内连接字符串。每个循环迭代构建一个**新字符串**。结果在字符串池中,你得到了n个不同的字符串对象!如果你必须在循环中完成,那么** StringBuilder **就是你的朋友。 –
我认为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";
}
}
你应该使用向下转换 – isaace
什么时候你的循环应该这样做?你永远不会改变'i'或'n',所以你的while循环将永远重复。 – azurefrog
另一种选择是使用String'concat'方法而不是'+'运算符 – tommyO