My program is supposed to count the number of occurrences a user inputted character appears in a string. For some reason, my program does not execute the for loop. Right after it prints out "Enter the string to search: ", it doesn't let me input a string and prints out: "There are 0 occurrences of '(inputted character)' in '(inputted string)'." on a new line. I need it to be able to find the occurrences of the character over any given amount of words inputted as the string. What can I do to make it function properly? Thanks.
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a character for which to search: ");
char ch = input.next().charAt(0);
System.out.println("Enter the string to search: ");
String str = input.nextLine();
int counter = 0;
for (int i = 0; i < str.length(); i++) {
if (ch == str.charAt(i)) {
counter++;
}
}
System.out.printf("There are %d occurrences of '%s' in '%s'.", counter, ch, str);
System.out.println();
}
}