Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Yahoo! Answers Question Response
- * Question URL: http://yhoo.it/1nDAhfI
- * Author: Jamie
- * TechnicalCafe.com
- */
- //import Scanner class to get user input
- import java.util.Scanner;
- public class LetterCount{
- public static void main(String [] args){
- //define and declare variables to hold the number of times
- //the letters c, d, h, m, and t have been found in a word
- int c = 0;
- int d = 0;
- int h = 0;
- int m = 0;
- int t = 0;
- //instantiate an object of the Scanner class so that
- //we can get user input
- Scanner input = new Scanner(System.in);
- //prompt the user to enter a word
- System.out.println("Please enter a word!");
- //define and declare a String variable to hold the value of
- //the word that is entered by the user and then use the Scanner
- //class object, called "input" to scan for a word (String)
- String word = input.nextLine();
- //use the ".length()" method of the String class to find out
- //how long the user-entered String is and store that value in
- //value of type "int"
- int wordLength = word.length();
- //Now that we know what the length of the String is, we can
- //use a for loop to iterate through each letter of the word
- //and use conditional statements to count how many times the
- //letters c, d, h, m, and t appear within that String/word
- for(int i = 0; i < wordLength; i++){
- if(word.substring(i, i+1).equals("c") || word.substring(i, i+1).equals("C")){
- //increment the variable for the letter "c" by one
- c++;
- }
- else if(word.substring(i, i+1).equals("d") || word.substring(i, i+1).equals("D")){
- //increment the variable for the letter "d" by one
- d++;
- }
- else if(word.substring(i, i+1).equals("h") || word.substring(i, i+1).equals("H")){
- //increment the variable for the letter "h" by one
- h++;
- }
- else if(word.substring(i, i+1).equals("m") || word.substring(i, i+1).equals("M")){
- //increment the variable for the letter "m" by one
- m++;
- }
- else if(word.substring(i, i+1).equals("t") || word.substring(i, i+1).equals("T")){
- //increment the variable for the letter "t" by one
- t++;
- }
- else{
- //if the word does not contain any of the five letters
- //the program is counting, then we can just ignore that
- //letter and move on to the next letter within the word
- }
- }
- //Now that the loop has finished iterating, we can use some
- //System.out.println() statements to print the results of the
- //count to the user
- System.out.println("Results of letter count in the word:"
- + " " + word + ":");
- System.out.println("c:" + c);
- System.out.println("d:" + d);
- System.out.println("h:" + h);
- System.out.println("m:" + m);
- System.out.println("t:" + t);
- }
- }
Add Comment
Please, Sign In to add comment