CharacterCounter.html Download CharacterCounter.html (759 Bytes) Write a complet
ID: 3588597 • Letter: C
Question
CharacterCounter.html Download CharacterCounter.html (759 Bytes) Write a complete Java program called "CharacterCounter" without the quotation marks) that .Prompts the user for two Strings called "inputWord" and "inputCharacter ·Checks whether inputCharacter has length fit doesnt, give the user appropriate feedback and end he program it does, ase awnie loop to count the number of times inputCharacter occurs in inputWord. Prints one of the following: "There are n occurrences of X in Y". or "There is 1 occurrence of X in Y". where n is a number equal to 0 or greater than 1, X is the value of inputCharacter, and Y is the value of inputWord.Explanation / Answer
Program CharacterCounter
import java.util.Scanner;
public class CharacterCounter{
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String inputWord, inputCharacter; // for accepting user input
Scanner in = new Scanner(System.in); //to get input from user
System.out.println("Enter the string :"); //displays the message
inputWord = in.nextLine();//accepts the line of strings till newline
System.out.println("Enter the character :");//displays the message
inputCharacter = in.next();//accepts the string
int count = 0;// variable to count the number of occurance
int i = 0; //counter variable
//if inputCharacter length is 1 then finds number of occurence else displays invalid
if (inputCharacter.length() == 1) {
do {
if (inputWord.charAt(i) == inputCharacter.charAt(0)) {
count++;
}
i++;
} while (i < inputWord.length());
System.out.println("There are " + count + " number of occurance of " + inputWord + " in " + inputCharacter);
} else {
System.out.println("sorry, invalid!!! enter single character");
}
}
}
Out Put
run:
Enter the string :
Hello World
Enter the character :
l
There are 3 number of occurance of Hello World in l
BUILD SUCCESSFUL (total time: 20 seconds)