Post

Created by @nathanedwards
 at November 4th 2023, 9:35:50 pm.

AP Computer Science Exam Question - Control Flow

Consider the following problem statement:

You are given a string inputStr, which contains a sentence. Write a method countVowelsAndConsonants that takes inputStr as input and counts the number of vowels and consonants in the sentence. Your method should return a string in the format "Vowels: #, Consonants: #".

For the purposes of this problem, vowels are defined as 'a', 'e', 'i', 'o', and 'u'. Input string can contain uppercase and lowercase letters.

Implement the countVowelsAndConsonants method with the following signature:

public static String countVowelsAndConsonants(String inputStr)

Example: Input:

countVowelsAndConsonants("Hello, World!")

Output:

"Vowels: 3, Consonants: 7"

Provide the implementation for the countVowelsAndConsonants method.

Note:

  • You can assume that the input sentence is not null and not empty.

Solution:

public static String countVowelsAndConsonants(String inputStr) {
    int vowelCount = 0;
    int consonantCount = 0;

    // Convert the input string to lowercase to handle both lowercase and uppercase vowels
    inputStr = inputStr.toLowerCase();

    // Iterate through each character in the input string
    for (int i = 0; i < inputStr.length(); i++) {
        char c = inputStr.charAt(i);

        // Check if the character is a vowel
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
            vowelCount++;
        }
        // Check if the character is a consonant
        else if ((c >= 'a' && c <= 'z') && !(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')) {
            consonantCount++;
        }
    }

    return "Vowels: " + vowelCount + ", Consonants: " + consonantCount;
}

Explanation:

  1. We define two variables vowelCount and consonantCount to keep track of the number of vowels and consonants respectively.
  2. We convert the inputStr to lowercase using the toLowerCase() method, so that we can handle both lowercase and uppercase vowels.
  3. We then iterate through each character in the inputStr using a for loop.
  4. For each character, we check if it is a vowel using the logical OR (||) operator, comparing it against the vowels 'a', 'e', 'i', 'o', and 'u'. If it is, we increment the vowelCount.
  5. We also check if the character is not a vowel and is a lowercase letter using the logical AND (&&) operator. We exclude uppercase letters and non-alphabetic characters from being counted as consonants. If it is a lowercase consonant, we increment the consonantCount.
  6. Finally, we return the count of vowels and consonants as a string in the specified format, using concatenation (+ operator).

This implementation has a time complexity of O(n), where n is the length of the input string.