错误提示
StringTest_2.java:25: 错误: 找不到符号
while((index=indexOf(key))!=-1)
^
符号: 方法 indexof(String)
位置: 类 StringTest_2
1 个错误
代码如下
public class StringTest_2
{
public static void main(String[] args)
{
String str="abcbjfbeabcjefjabcjepofkjabcniabc";
String key="abc";
int count=getKeyStringCount(str,key);
System.out.println("count="+count);
}
public static int getKeyStringCount(String str,String key)
{
//定义计数器
int count=0;
//定义变量记录key出现的位置
int index=0;
while((index=indexOf(key))!=-1)
{
str=str.substring(index+key.length());
count++;
}
return count;
}
}
常见的找不到符号就是符合错误或没有定义符号,我检查了符号没有错误,又试了导包,都没用。
后面发现while((index=indexOf(key))!=-1)一句中indexOf(key)没有用str对象调用,int indexOf(String str)的作用是返回指定字符串第一次出现在字符串的索引,没有调用字符串对象就不能就不能实现其功能!
解决方法
所以就是将while((index=indexOf(key))!=-1)
改成while((index=str.indexOf(key))!=-1)