The printing looks good
Now if you are getting a "String index out of range: 0" message from the line "if(srchTerm.charAt(i) == userStr.charAt(i))" it looks very much as if you are checking
userStr at an "illegal" position. I mean at a position beyond where the string ends. It would be a good plan to check what the value of
userStr really is:
public boolean searchWord(String srchTerm)
{
System.out.println("Searching for -->|" + srchTerm + "|<--");
boolean srch = false;//initializes srch variable
for(int i = 0; i < userStr.length(); i++)
{
if(srchTerm.charAt(i) == userStr.charAt(i))
{
srch = true;//redefines srch
break;
}else
{
srch = false;//redefines srch
}
}
return(srch);
}
The reason for the arrows and things is that I'd wonder about the search term being an empty string. (And the reason for that was the zero mentioned in the exception as being the invalid character position. The only string that doesn't have a zero position is the empty string.)
Try that and see what you are searching for.
---
Really do run the code above! Otherwise what follows will be a spoiler.
The while loop of your driver looks like this:
Scanner in = new Scanner(System.in);
System.out.print("Enter Your Words! (Separate with commas (,) End with period (.))\n");
String userInput = in.nextLine();//receives the user input
SearchMyString str = new SearchMyString(userInput);//holds the user input
str.displayMenu();
int ans = in.nextInt(); /* ===A=== */
if(ans == 1){
// ...
}else if(ans == 2){
// ...
}else if(ans == 3){
System.out.print("==============================\n\n");
System.out.print("Please enter the word you would like to search for:\n\n");
String word = in.nextLine(); /* ===B=== */
SearchMyString newSearch = new SearchMyString(word);
int srch = str.searchWord(word);
// ...
}
// ...
The nextInt() call on the line I've marked A is interesting. It reads and returns an int. But, more subtly, it leaves the scanner pointing just past where the int ends. Ie it leaves the scanner
just before the new line. And this has an unfortunate consequence: when, at the line I've marked B, you call nextLine() you will get an empty string returned. That's because nextLine() returns everything up to the newline (which will be nothing) and then skips over the new line.
(Moreover nextLine() will return the empty string straight away. It won't wait for anything to be entered.)
The fix depends on this behaviour of nextLine() - on the fact that it skips over the newline. It is to put a nextLine() call just after the nextInt().
Scanner in = new Scanner(System.in);
System.out.print("Enter Your Words! (Separate with commas (,) End with period (.))\n");
String userInput = in.nextLine();//receives the user input
SearchMyString str = new SearchMyString(userInput);//holds the user input
str.displayMenu();
int ans = in.nextInt(); /* ===A=== */
in.nextLine(); // advance to the next line
// ...