public class CharacterCounter{
public static void main(String[] args){
//Step 1: Getting input from the user.
System.out.println("Enter a character: ");
char character = (System.console().readLine()).charAt(0);
System.out.println("Enter a string: ");
String sentence = (String) System.console().readLine();
/*Step 2: Creating our variable to keep track of how many times
the character occurs.*/
int count = 0;
//Step 3: Loop through the string to check each character.
for(int i = 0; i < sentence.length(); i++){
char tempChar = sentence.charAt(i);
if(tempChar == character){
count++;
}
}
//Step 4: Print the number of times that the character occurred.
System.out.println("Found the character " + count + " times.");
}
}
This is an example program I wrote to demonstrate how to solve programming problems. You can read more about it here: https://medium.com/p/8e9b2a6eef02/.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.