【发布时间】:2015-04-22 21:09:46
【问题描述】:
我在 Java 中有以下代码:
public class StringSearch
{
public static void main(String[] args)
{
String s = new String("I love my school. I love to play basketball. It is lovely weather. Love is life.");
System.out.println(s);
int i = -1;
int count = 0;
System.out.print("Counting love:");
do{
i = s.findW("love");
if(i != -1){
count++;
System.out.print(count+" ");
}
}while(i != -1);
System.out.println("The word \"love\" appears "+count+" times.");
}
}
我知道 s.findW() 是不正确的,因为 findW() 没有为 Class String 定义。但是,是否可以在 String 类中添加用户定义的函数并修复此问题?
有什么办法可以解决这个问题吗?
此问题的提示是阅读 JDK 文档并修复代码。 :/
【问题讨论】:
-
“是否可以在类 String 中添加用户定义的函数”
String类是final,如文档中所述。您可以将此方法添加到其他类型,或使用其他方法,如contains或indexOf(文档中也提到) -
“这个问题的提示是阅读 JDK 文档并修复代码。” 那么这是一个测验吗?
-
创建自己的
findW(String string)方法并使用它?这是什么? -
参见 String.indexOf...
标签: java string user-defined-functions