Java方法被打破了

时间:2014-10-29 23:28:16

标签: java methods return compression static-methods

我试图让它返回一个压缩的单词。例如,反应应该是@ act $。但它会以反应$返回。我觉得我的问题不包括返回声明中的原始单词。有人可以帮忙吗?谢谢!

public static String compress (String word) {
      String newWord = "";
      int the = word.indexOf("the");
      if (the >= 0) {
         newWord = word.substring(0,the) + "&" + word.substring(the+3);
      }
      int ion = newWord.indexOf("ion");
      if (ion >= 0) {
         newWord = newWord.substring(0,ion) + "$" + word.substring(ion+3);
      }
      int ing = newWord.indexOf("ing");
      if (ing >= 0) {
         newWord = newWord.substring(0,ing) + "~" + word.substring(ing+3);
      }
      int an = newWord.indexOf("an");
      if (an >= 0) {
         newWord = newWord.substring(0,an) + "#" + word.substring(an+2);
      }
      int re = newWord.indexOf("re");
      if (re >= 0) {
         newWord = newWord.substring(0,re) + "@" + word.substring(re+2);
      }
      int con = newWord.indexOf("con");
      if (con >= 0) {
         newWord = newWord.substring(0,con) + "%" + word.substring(con+3);
      }
      return newWord;
   }

2 个答案:

答案 0 :(得分:2)

压缩版本:

public static String compress(String word) {
    word = word.replace("the", "&");
    word = word.replace("ion", "$");
    word = word.replace("ing", "~");
    word = word.replace("an", "#");
    word = word.replace("re","@");
    word = word.replace("con","%");    
    return word;
}

答案 1 :(得分:1)

您以混乱的方式混淆了对newWordword的使用。如果第一个if子句没有触发,newWord仍然是一个空字符串,其他任何条件都不会触发。另一方面,如果newWord确实被设置为某种内容,您仍然会继续使用word子字符串,而这些方法没有任何意义。

通过整个方法只使用一个变量会更好。

public static String compress(String word) {
    int the = word.indexOf("the");
    if (the >= 0) {
        word = word.substring(0,the) + "&" + word.substring(the+3);
    }
    int ion = word.indexOf("ion");
    if (ion >= 0) {
        word = word.substring(0,ion) + "$" + word.substring(ion+3);
    }
    int ing = word.indexOf("ing");
    if (ing >= 0) {
        word = word.substring(0,ing) + "~" + word.substring(ing+3);
    }
    int an = word.indexOf("an");
    if (an >= 0) {
        word = word.substring(0,an) + "#" + word.substring(an+2);
    }
    int re = word.indexOf("re");
    if (re >= 0) {
        word = word.substring(0,re) + "@" + word.substring(re+2);
    }
    int con = word.indexOf("con");
    if (con >= 0) {
        word = word.substring(0,con) + "%" + word.substring(con+3);
    }
    return word;
}

另请注意,以这种方式编写,每个单词只能使用一次替换:如果您有"thethe",则会将其压缩为"&the",而不是"&&"。如果要多次使用替换,则必须使用循环。或者,更方便的是,使用String.replace