The following code is not correct. When I enter the string, "The rain in Spain" the output is 0 when it should be 2. Or when I put "in in in" the output is 1 when it should be 3. So please help me out and show me how to change this to make it work. Thanks!
import java.util.Scanner;
public class Assignment5b {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the string: ");
String str = keyboard.next();
String findStr = "in";
int lastIndex = 0;
int count =0;
while(lastIndex != -1){
lastIndex = str.indexOf(findStr,lastIndex);
if( lastIndex != -1){
count ++;
lastIndex+=findStr.length();
}
}
System.out.print("Pattern matches: " + count);
}}