public static void main(String [] args)
{
String i = "Hello world Hello";
String test = "Hello";

int count = 0;
int index = 0;
do
{
count ++;
index = i.indexOf(test); //在i中搜索Hello字符
index += test.length(); // 获得下一个开始索引
index = i.indexOf(test, index); //在指定索引处继续往后搜索

}while(index!=-1); //index不等于-1时继续执行上述代码查找字符。
System.out.println(count);
}我的原意是编写一个程序,这个程序计算字符串中Hello字符出现的次数,可是陷入了死循环,怎么都看不出到底是哪里导致的,而且我点击编译运行,机器变得异常的卡,机器配置本来就不高,请看出哪里错误的朋友指出,谢谢~。

解决方案 »

  1.   

    index = i.indexOf(test, index); //在指定索引处继续往后搜索
    while(index!=-1); 
    i没有任何处理,所以index = i.indexOf(test, index);永远也不可能是-1的
      

  2.   

    你的字符串里面一直有hello,indexOf不可能返回-1吧
      

  3.   


    indexOf在没有找到的时候不是会自动返回-1吗??
      

  4.   

    每次循环index都被 index = i.indexOf(test); //在i中搜索Hello字符 这句代码重新赋值为0
      

  5.   

    在循环最后一句,你可以输出下你的index,应该一直是5
      

  6.   

    第11行替换成 index = i.indexOf(test, index); //在i中搜索Hello字符,应该就可以了。试试。
      

  7.   

    针对你的代码可以将count++下面的一行改成 index=i.indexOf(test,index);
    楼主可以考虑这个代码 public static void main(String [] args){    
    String i = "Hello world Hello Hello Hello";    
    String test = "Hello";         
    int count = -1;    
    int index = 0;    
    do {        
    count ++; 
    index = i.indexOf(test); 
    i = i.substring(index+1);
    }while(index!=-1); //index不等于-1时继续执行上述代码查找字符。   
    System.out.println(count);
    }
      

  8.   


    indexOf在没有找到的时候不是会自动返回-1吗??
    问题是你的indexOf的源字符一直都是“Hello world Hello”,木有改变,indexOf方法返回的值当然都是同一个了,当然得死循环