The problem
Write a program that asks the user to enter a string and then asks the user to enter a character. The program should count and display the number of times that the specified character appears in the string.
Breaking it down
Create variables
String stringToSearch; // The string to search
String letter = null; // The letter to count
Get user's input
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get a string from the user.
System.out.print("Enter a string:");
stringToSearch = keyboard.nextLine();
// Retrieve the letter to count.
System.out.print("Enter a letter contained in the string:");
letter = keyboard.nextLine();
Count the number of times a letters in string
// Get the letter to count.
double numberOfLettersInString = countLetters(stringToSearch, letter);
static double countLetters (String stringToSearch, String letter) {
checkNotNull(stringToSearch);
checkNotNull(letter);
return StringUtils.countMatches(stringToSearch, letter);
}
Display output
System.out.println("The letter " + letter + " appears " + numberOfLettersInString + " times in the string:\n" + stringToSearch);
Output
Enter a string:running down the road
Enter a letter contained in the string:r
The letter r appears 2.0 times in the string:
running down the road
Unit tests
@Test(expected=NullPointerException.class)
public void count_letters_null_to_search () {
CharacterCounter.countLetters(null, "");
}
@Test(expected=NullPointerException.class)
public void count_letters_null_letter () {
CharacterCounter.countLetters("", null);
}
@Test
public void count_letters () {
double count = CharacterCounter.countLetters("aaaa", "a");
assertTrue(count == 4);
}
Level Up
- if apache common's StringUtils wasn't available, what the algroithm look like?
- validate users input
- determine a better way to output the information