Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 错误:二进制运算符'+';_Java_Concatenation - Fatal编程技术网

Java 错误:二进制运算符'+';

Java 错误:二进制运算符'+';,java,concatenation,Java,Concatenation,我这里有一个代码,它将使用一个名为的字符串来重复它,并在同一行中重复n次。例如,toRepeat=*,n=3,result=*** public class RepeatIt { public static String repeatString(final Object toRepeat, final int n) { int i = 0; if (toRepeat instanceof String) { while (i &l

我这里有一个代码,它将使用一个名为
的字符串来重复它,并在同一行中重复n次。例如,toRepeat=*,n=3,result=***

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";
        }
    }
}
公共类RepeatIt{
公共静态字符串repeatString(最终对象重复,最终整数n){
int i=0;
if(重复字符串的实例){
而(i
但是,我在2
toRepeat
之间的
+
符号上得到一个错误,它表示二进制运算符
+
的操作数类型不正确。如果您知道我如何解决此问题,请告诉我,我将不胜感激。

您可以更改

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

这里实际上有三个错误: 第一个是
toRepeat
的类型
Object
(它是
final
,即您不能分配新值):对象没有
+
。您可以将其转换为
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";
    }
}

您应该使用downcasting循环应该在什么时候执行?您永远不会更改
i
n
,这样您的while循环将永远重复。另一种选择是使用String
concat
方法而不是
+
运算符for循环可能更容易。不要使用它!!!这是一个大错误。不要在循环中连接字符串。每个循环迭代生成一个新字符串。因此,在字符串池中,您将获得n个不同的字符串对象!!如果必须在循环中执行,那么StringBuilder就是您的朋友。@oleg.cherednik同意,但解决方案最初不是解决性能影响,而是进行了编辑以解决这一问题。谢谢。@CWilliams如果这有帮助,请接受它作为一个答案,让它对未来的读者也有用。我曾经这样做过,但现在我面临另一个问题,正如另一个答案所说的那样,如果我增加I++的话,第一次循环后的结果将等于**,****在第二个循环之后*******在第三个循环之后,依此类推,我现在正试图找到一个解决方案,所以我修复了其他问题,但I如何增加I,使其仅增加1个值?不要用类似tr+tr的串联替换字符串,而是将原始值concat:tr+toRepeat。
String tr = (String)toRepeat; // this would be *
String finalVal = ""; 
while (i < n){
    final = finalVal + tr; // would add * for each iteration
    i++; 
}
return finalVal;
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";
    }
}