I am trying to create a findText() method to find a word or phrase in a String.
static String usrStr = "There was was once a boy named Timmy. Timmy liked to play in the park.";
public static void findText() {
int matchCntr = 0;
int numInstances = 0;
String phrase = "";
System.out.println("Enter a word or phrase to be found: ");
phrase = scnr.nextLine();
for (int i = 0; i < usrStr.length(); i++) {
if (usrStr.charAt(i) == phrase.charAt(matchCntr)) { //FIX ME
matchCntr++;
if (matchCntr == phrase.length()) {
numInstances++;
matchCntr = 0;
}
}
else {
matchCntr = 0;
}
}
System.out.println("\"" + phrase + "\" instances: " + numInstances);
return;
If it worked correctly I should get this ouput:
Enter a word or phrase to be entered: <Timmy>
"Timmy" instances: 2
But when I run this code I get this error. I marked where the error occurs in the main body of code with a //FIX ME.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 0
I read that this error is probably because the string "phrase" is not at least 38 characters, but that still doesn't help me fix the code. Do you have any solutions for how to fix this piece of code to work as intended while avoiding the StringIndexOutOfBoundsException error?