import java.io.*;
public class Search {
   public static void main(String args[]) {
   int first = 0, second =0, count = 0;
   String text = "So that account you never had at a bank you never";   
   String s = "";
   String subText = text;
   System.out.println(text);
   System.out.println("请输入单词");
   try {
   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   s = in.readLine();
   } catch(IOException e){}
   for(int i=1; i<=text.length();i+=second+1) {
   second = subText.indexOf(" ");
   String temp = subText.substring(first, second);
   if(s.equalsIgnoreCase(temp)) count++;
      
   subText = subText.substring(second+1);       
  
   }
   if(count==0)
   System.out.println("单词"+s+"没有出现");
   else
   System.out.println("单词"+s+"出现了"+count);
   }
}
抛出StringIndexOutOfBoundsException
多多指点,小妹谢谢了

解决方案 »

  1.   

    因为循环到最后一个单词 nerver的时候,second = subText.indexOf(" "); 这个时候字符串中只剩下never没有空格,所以seconde = -1String temp = subText.substring(first, second); 这样的这段代码就出问题了。
    可以在前面加个判断,
    if(second > 0){
    String temp = subText.substring(first, second); 
    }
      

  2.   


    import java.io.*; 
    public class TestBuffer{ 
      public static void main(String args[]) { 
      int count = 0; 
      String text = "So that account you never had at a bank you never";   
      String s = ""; 
      System.out.println(text); 
      System.out.println("请输入单词"); 
      try { 
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
      s = in.readLine(); 
      } catch(IOException e){} 
      String[] textarr = text.split(" ");
      for(int i=1; i <textarr.length;i++) { 
    String temp = textarr[i];
    if(s.equalsIgnoreCase(temp)) count++; 
      } 
      if(count==0) 
      System.out.println("单词"+s+"没有出现"); 
      else 
      System.out.println("单词"+s+"出现了"+count); 
      } 

      

  3.   

    请参考 http://www.jspcn.net/htmlnews/11171163972961452.html