Answer:
This is the JAVA code:
import java.util.Scanner; // to obtain user input
//class designed to count occurrences of a character within a string
public class CharacterCounter
//method that calculates how many times a character appears within a string
{ public static int CountCharacter(String userString, char character)
{
int counter = 0; //keeps track of the number of times the character appears in the string
for (int i=0; i<userString.length(); i++) //iterates over every character in the string
{ // if the character aligns with the one sought in the string
if (userString.charAt(i) == character)
counter++; // increments the character count variable
}
return counter; } // returns the count of the character found in the string
public static void main(String[] args) {
Scanner scanner = new Scanner(System. in);// accepts user input
String string;
char character;
System.out.println("Enter a string"); // prompts the user for a string
string = scanner.nextLine(); //captures the input string
System.out.println("Enter a character");
// requests the character input from the user
character = scanner.next().charAt(0); //captures and reads the character
System.out.println("number of times character "+character + " appears in the string " + string +": " + CountCharacter(string, character)); } }
// calls CountCharacter method to display the frequency of a character in the input string
Explanation:
The CountCharacter() method contains a loop where index variable i traverses through each character of the string, incrementing the counter variable by 1 each time the sought character matches. This indicates that the counter maintains the tally of occurrences of the character in the string. The loop terminates when i exceeds the string length, which means the full string has been scanned for the specified character. Finally, the count variable yields the number of times the character was found in the string. The main() function receives user inputs for a string and a character to search for within that string. It subsequently invokes the CountCharacter() function to determine how many times the designated character appears in the specified string, displaying the result on the screen.
The program's output is provided in the attached screenshot.