首页 文章

错误:二元运算符的错误操作数类型'+'

提问于
浏览
-1

我这里有一个代码,它将采用一个名为 toRepeat 的字符串,并在同一行中重复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";
        }
    }
}

但是我在2 toRepeat 之间的 + 符号上出现错误,该符号表示二进制运算符 + 的错误操作数类型 . 如果你知道如何解决这个问题,请告诉我,我会非常感激 .

3 回答

  • 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;
    

    Edit :正如@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

    这里实际上有三个错误:第一个是 toRepeat 的类型 Object (它是 final ,即你可能没有分配新的值):对象没有 + . 您可以将其转换为 String ,如之前的答案中所示 . 第二:你的循环没有终止,因为 i 保持 0 . 第三:如果你增加 i (例如循环中的 i += 1 ) . 在第一个循环之后,您将获得 ** ,在第二个循环之后将获得 **** ,在第三个循环之后将获得8个星 .

  • 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";
        }
    }
    

相关问题