0

回答前注意:不要说我可以使用正则表达式,拆分,替换......因为我知道,我需要专门这样做。

我有以下代码,我尝试将“for”替换为 4,将“and”替换为 &,将“you”替换为 U,将“to”替换为 2。我对此有疑问。一是我不知道如何创建一个始终允许我添加自身的 String 对象,即在我去的时候添加更多的单词。第二个问题是变量“space”(找到indexOf“”)在第一次运行代码后等于0,我不明白为什么。

代码:

    public static void shorthand(String sentence){
    //if I put String completeSentence; it says the variable might not have been initialized and wont let me run. 

    if (sentence.length() > 0){
        int space = sentence.indexOf(" ");
        String completeSentence = ""; //however if I put this here I just reset my value all the time and cant see the full string after it all adds up.
        if (space == -1){
            if (sentence.equalsIgnoreCase("to")){
                completeSentence += "to";
            } else if(sentence.equalsIgnoreCase("for")){
                completeSentence += "4";
            } else if (sentence.equalsIgnoreCase("you")){
                completeSentence += "you";
            } else if(sentence.equalsIgnoreCase("and")){
                completeSentence += "&";
            } else {
                completeSentence += sentence;
            }
            System.out.println(completeSentence);
        } else {
            String word = sentence.substring(0,space);
            if (word.equalsIgnoreCase("to")){
                completeSentence += "to";
            } else if(word.equalsIgnoreCase("for")){
                completeSentence += "4";
            } else if (word.equalsIgnoreCase("you")){
                completeSentence += "you";
            } else if(word.equalsIgnoreCase("and")){
                completeSentence += "&";
            } else {
                completeSentence += word;
            }
            shorthand(sentence.substring(space));
        }
    }
}  

主要的:

public class Main {
public static void main (String [] args){
    Scanner in = new Scanner(System.in);
    String word = in.nextLine();
    Functions.shorthand(word);
}
}

我可以做些什么来添加相同的字符串,以便最后我可以看到我的完整句子?还有为什么我space = 0在第一次运行代码之后?

4

1 回答 1

0

//如果我把String completeSentence; 它说变量可能尚未初始化并且不会让我运行。

那是因为你需要给它一个初始值,比如:

String completeSentence = "";

但是,StringBuilder在这种情况下使用 a 可能会更好(即使编译器可能会尝试隐式优化您当前的策略)

于 2013-11-05T20:25:35.817 回答