我在这里有一个代码,它需要一个名为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