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:
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:
vowelCount
and consonantCount
to keep track of the number of vowels and consonants respectively.inputStr
to lowercase using the toLowerCase()
method, so that we can handle both lowercase and uppercase vowels.inputStr
using a for loop.||
) operator, comparing it against the vowels 'a', 'e', 'i', 'o', and 'u'. If it is, we increment the vowelCount
.&&
) operator. We exclude uppercase letters and non-alphabetic characters from being counted as consonants. If it is a lowercase consonant, we increment the consonantCount
.+
operator).This implementation has a time complexity of O(n), where n is the length of the input string.