-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVowelsConsonants.java
73 lines (53 loc) · 1.96 KB
/
VowelsConsonants.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.feb7;
import java.util.Scanner;
/*
* Problem: take one string array and calculate count how many vowels are and constants
*/
public class VowelsConsonants {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Taking input of string array
System.out.print("Enter the number of strings in the array: ");
int n = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
String[] strings = new String[n];
System.out.println("Enter the strings:");
for (int i = 0; i < n; i++) {
strings[i] = scanner.nextLine();
}
// Calculate total counts
int totalVowels = 0;
int totalConsonants = 0;
for (String str : strings) {
int[] counts = countVowelsAndConsonants(str);
totalVowels += counts[0];
totalConsonants += counts[1];
}
// Display total counts
System.out.println("Total Vowels across all strings: " + totalVowels);
System.out.println("Total Consonants across all strings: " + totalConsonants);
scanner.close();
}
private static int[] countVowelsAndConsonants(String str) {
int vowelCount = 0;
int consonantCount = 0;
for (char ch : str.toCharArray()) {
if (isAlphabetic(ch)) {
// Check if the character is a vowel
if (isVowel(ch)) {
vowelCount++;
} else {
consonantCount++;
}
}
}
return new int[]{vowelCount, consonantCount};
}
private static boolean isAlphabetic(char ch) {
return Character.isLetter(ch);
}
private static boolean isVowel(char ch) {
char lowerCh = Character.toLowerCase(ch);
return lowerCh == 'a' || lowerCh == 'e' || lowerCh == 'i' || lowerCh == 'o' || lowerCh == 'u';
}
}