2013-11-22 258 views
0

所以我的代码工作的一些话,但不是别人它冲刺了字符串索引超出范围:-1 IM想每个元音和元音集群 EX可疑之前打印出来UB将dubububious或猫loveo将lubovudeo字符串错误

字符串犯罪,设置;

 sentance = "toster iooppp"; 
     set= translate(sentance); 
     System.out.println(set); 
} 
public static String translate (String sentence){ 

    String set = " "; 
    sentence= sentence.toLowerCase(); 
    scan = new Scanner (sentence); 

    while (scan.hasNext()) { 

     set+= toUbbi (scan.next()); 
     set += " "; 
    } 
    return set; 
    } 

private static String toUbbi(String word) { 
    String str= word; 
    String new_str=""; 
    for (int i = 0; i < str.length(); i++) { 
      char c = str.charAt(i); 
      if (isVowel(c) && isVowel(str.charAt(i -1))) 
      { // If is a vowel 
       new_str += "ub" ; 
      } 
      new_str += c; 
     } 
    return new_str; 
    } 


    private static boolean isVowel(char c) 
    { 
     if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){ 
      return true;} 

     return false;  
+0

此代码是不完整 - 两边缺少线条。 – isnot2bad

+0

不会猫爱是lubovububeo? –

+0

我怀疑你的逻辑是不正确的,你可能会发现当你不让它崩溃时它会给你错误的答案。我会手工完成它,看看'toUbi'将如何工作。还要确保逻辑在界限处做你想做的事情,即当'i'为0并且当它是'str.length() - 1'时。 – ajb

回答

0

在第一次迭代中提示错误..

 if (isVowel(c) && isVowel(str.charAt(i -1))) 
     { // If is a vowel 
      new_str += "ub" ; 
     } 

所以改变这样的..

 if (isVowel(c)) 
     { // If is a vowel 
      new_str += "ub" ; 
     } 

或更改你的循环..

for (int i = 1; i < str.length(); i++) { 
     // yur remain code... 
    }