Write a method that finds the number of occurrences of a specified character in a string using the following header
LANGUAGE: JAVA
CHALLENGE:
(Occurrences of a specified character )
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)
Add a main method to the class that tests the method by prompting for a string and a character,
invoking the method and printing the returned count.
SOLUTION:
import java.util.*; public class Occurrence{ public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.print("Enter a word: "); String str = input.nextLine(); System.out.print("Enter a letter: "); char a = input.nextLine().charAt(0); int letterCheck = Occurrence.count(str, a); System.out.println("The word was: " + str); System.out.println("The letter " + a + " was found this many times: " + letterCheck); } public static int count(String str, char a){ int count = 0; for (int i = 0; i < str.length(); i++){ if (str.charAt(i) == a){ count++; } } return count; } }