/**
 * NumOccur.java
 *
 * Computer Science S-111
 * 
 * Demonstrates: 
 *   - the use of a for loop to perform a cumulative computation (counting)
 *   - the use of a for loop to iterate over the characters in a String
 */

import java.util.*;

public class NumOccur {
    /**
     * numOccur - counts the number of times that the character ch appears
     * in the string str. 
     */
    public static int numOccur(char ch, String str) {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ch) {
                count++;
            }
        }
        return count;
    }
    
    /*
     * A main method with test code based on user inputs.
     */ 
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        
        System.out.print("Enter a word: ");
        String word = console.next();
        System.out.print("Enter a letter to count: ");
        
        // There is no nextChar() method, so we use next() and
        // extract the first character in the resulting String.
        String letterStr = console.next();
        char letter = letterStr.charAt(0);
        
        int count = numOccur(letter, word);
        System.out.print(letter + " appears " + count);
        System.out.println(" time(s) in " + word + ".");
    }
}
