获取String超出范围的异常

时间:2016-03-20 19:35:53

标签: java

代码编译并且也适用于传递的任何字符串,但它不用于检查元音。它抛出一个字符串越界错误,我不知道为什么。对辅音的检查正在进行中。

以下是代码:

public String catchword(String word){
     int x = 0;
     for(x=0; x<word.length()+1; x++){  
         boolean v = Vowel(word.charAt(x));
         boolean c = Consonant(word.charAt(x));
         if (x<word.length()-1){
             v = Vowel(word.charAt(x+1));
         } else{
             v = true;
         }

         if (c == true && v == true){
             word = word.substring(0,x+1) + "op" + word.substring(x+1,word.length());
             x = x+3;
         } 
     }
     System.out.print(word);
     return word;
 }

1 个答案:

答案 0 :(得分:0)

for(x=0; x<word.length()+1; x++)

x<word.length()+1

应该是

x<word.length()-1

word的最大索引为word.length()-1

word.charAt(x+1)您也会遇到问题。 word.length() - 1是最大索引,当x等于它时,您将再次获得IndexOutOfBoundsException