The problem
Write a method that finds the number of occurrences of a specified character in a string using the following header: public static int count(String str, char a)
For example, count("Welcome", 'e') returns 2. Write a test program that prompts the user to enter a string followed by a character and displays the number of occurrences of the character in the string.
Breaking it down
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
String sentence = input.nextLine();
System.out.print("Enter a character: ");
String ch = input.next();
input.close();
Map<String, Long> frequentChars = Arrays.stream(
sentence.toLowerCase().split("")).collect(
Collectors.groupingBy(c -> c, Collectors.counting()));
System.out.println("The number of occurrences of
" + ch + " in \""
+ sentence + "\" is " + frequentChars.get(ch));
}Output
Enter a string: welcome
Enter a character: e
The number of occurrences of 'e' in "welcome" is 2