Skip to content

Commit f4915d6

Browse files
committed
[Manan] ADD:Counting the total number of vowels and consonants in a given string
1 parent 43f239d commit f4915d6

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

VowelsAndConsonants.java

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import java.util.Scanner;
2+
3+
class VowelsAndConsonants {
4+
// Method to calculate the length of the String
5+
public static int stringLength(String s) {
6+
int count = 0;
7+
try {
8+
while (true) {
9+
s.charAt(count); // Try to access the character at index 'count'
10+
count++; // Increment the counter if possible.
11+
}
12+
} catch (IndexOutOfBoundsException e) {
13+
// Exception occurs when we go beyond the last index, so return count
14+
}
15+
return count;
16+
}
17+
18+
// Method to check if a character is a vowel, consonant, or not a letter
19+
public static String checkCharacterType(char ch) {
20+
// Convert to lowercase if uppercase
21+
if (ch >= 'A' && ch <= 'Z') {
22+
ch = (char) (ch + 32);
23+
}
24+
25+
// Check if it's a vowel
26+
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
27+
return "Vowel";
28+
}
29+
// Check if it's a consonant (a letter but not a vowel)
30+
else if (ch >= 'a' && ch <= 'z') {
31+
return "Consonant";
32+
}
33+
// Not a letter
34+
return "Not a Letter";
35+
}
36+
37+
// Method to count vowels and consonants in a string
38+
public static int[] countVowelsAndConsonants(String text) {
39+
int vowels = 0, consonants = 0;
40+
int n = stringLength(text);
41+
42+
for (int i = 0; i < n; i++) {
43+
String type = checkCharacterType(text.charAt(i));
44+
if (type.equals("Vowel")) {
45+
vowels++;
46+
} else if (type.equals("Consonant")) {
47+
consonants++;
48+
}
49+
}
50+
return new int[]{vowels, consonants}; // Returning count in an array
51+
}
52+
53+
// Main method
54+
public static void main(String[] args) {
55+
Scanner input = new Scanner(System.in);
56+
57+
// Define a variable of type String and take user input
58+
System.out.print("Enter a string: ");
59+
String userInput = input.nextLine();
60+
61+
// Method to count vowels and consonants
62+
int[] count = countVowelsAndConsonants(userInput);
63+
64+
// Display the count of vowels and consonants
65+
System.out.println("Number of vowels: " + count[0]);
66+
System.out.println("Number of consonants: " + count[1]);
67+
}
68+
}

0 commit comments

Comments
 (0)