-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVowel.java
More file actions
56 lines (37 loc) · 1.41 KB
/
Vowel.java
File metadata and controls
56 lines (37 loc) · 1.41 KB
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
/*Question 6 : Count Vowels
* Write a program that counts the numbers of vowels in sentence.
*/
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Vowel {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = input.nextLine();
input.close();
// calls the method countVowels and prints the result
int count = cntVowels(sentence.toLowerCase());
System.out.println("Number of vowels is: " + count);
}
// Method to count the number of vowels in the sentence.
public static int cntVowels(String sentence) {
int count = 0;
// Set to store the vowels that have been seen
Set<Character> seen = new HashSet<>();
// use a loop to check each character in the sentence
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
// covert the character to lowercase
ch = Character.toLowerCase(ch);
// check if the character is a vowel and add it to the set if it is not
if (!seen.contains(ch)) {
count++;
seen.add(ch);
}
}
}
return count;
}
}