简体   繁体   English

有没有办法在调用这些方法时避免使用构造函数?

[英]Is there a way I can avoid using a constructor while calling these methods?

I have this code trying to modify the choice string by adding "wow" to the end of it.我有这段代码试图通过在它的末尾添加“哇”来修改选择字符串。 I am trying to use a custom class rather than just concatenating Strings because I want to be able to run other methods on it in the future as well.我正在尝试使用自定义类,而不仅仅是连接字符串,因为我希望将来也能够在其上运行其他方法。

for(String choice : commands) {
    count++;
    if(goAvailable.contains(choice)) {
        actionApnd("You went to " + new ModifyString(choice).append("wow") + ".");
        //System.err.print(choice + " ");
        break;
    } else if (count == commands.length) {
        actionApnd("Where did you want to go?");
    }

}

the ModifyString class (trimmed down): ModifyString 类(缩减):

public ModifyString(String str) {

    stringToReturn = str;
}

public String append(String toAppend) {

    stringToReturn += toAppend;

    return stringToReturn.trim();
}

I had this method in the ModifyString class and was using it instead of a constructor, but an error message told me I can't run append on the type String.我在ModifyString类中有这个方法并使用它而不是构造函数,但是一条错误消息告诉我我不能在类型 String 上运行append

public static String string(String str) {

    stringToReturn = str;
    return stringToReturn.trim();
}
public static String string(String str) {

    stringToReturn = str;
    return stringToReturn.trim();
}

The issue is that stringToReturn is an instance field on ModifyString , meaning that it's associated with a specific instance of that class.问题在于stringToReturnModifyString上的一个实例字段,这意味着它与该类的特定实例相关联。 There is no such instance in a static method. static方法中没有这样的实例。

It's unclear what you're trying to achieve, given that the return type is String : you could simply remove the first statement:鉴于返回类型是String ,目前尚不清楚您要实现的目标:您可以简单地删除第一条语句:

public static String string(String str) {
    return str.trim();
}

but then you may as well just invoke str.trim() directly.但是你也可以直接调用str.trim()

Alternatively, you may have meant to return an instance of ModifyString :或者,您可能打算返回ModifyString的实例:

public static ModifyString string(String str) {
    return new ModifyString(str.trim());
}

Note that string concatenation is a bad way to accumulate strings, because it requires copying the existing string in order to do the concatenation.请注意,字符串连接是累积字符串的一种糟糕方式,因为它需要复制现有字符串才能进行连接。

A better approach would be to use a StringBuilder , either directly, or wrapping it:更好的方法是直接使用StringBuilder或包装它:

class ModifyString {
  private final StringBuilder sb;

  ModifyString(String str) {
    sb = new StringBuilder(str.trim());
  }

  ModifyString append(String str) {
    sb.append(str.trim());
    return this;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM