QUESTİON__2
Wed May 24 2023 09:29:10 GMT+0000 (Coordinated Universal Time)
Saved by @Mohamedshariif #java
public static void count(String str)
{
// Initially initializing elements with zero
// as till now we have not traversed
int vowels = 0, consonants = 0;
// Declaring a all vowels String
// which contains all the vowels
String all_vowels = "aeiouAEIOU";
for (int i = 0; i < str.length(); i++) {
// Check for any special characters present
// in the given string
if ((str.charAt(i) >= 'A'
&& str.charAt(i) <= 'Z')
|| (str.charAt(i) >= 'a'
&& str.charAt(i) <= 'z')) {
if (all_vowels.indexOf(str.charAt(i)) != -1)
vowels++;
else if(str.charAt(i) >= 'A' || str.charAt(i)>= 'a' || str.charAt(i)<='z' || str.charAt(i)<='Z')
consonants++;
}
}
// Print and display number of vowels and consonants
// on console
System.out.println("Number of Vowels = " + vowels
+ "\nNumber of Consonants = "
+ consonants);
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Custom string as input
String str = "i am Mohamed Abdirizak";
// Calling the method 1
count(str);
}
}
// OUTPUT:
Number of Vowels = 9
Number of Consonants = 10
//ANOTHER WAY
import java.util.Scanner;
public class Exercise {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//Counter variable to store the count of vowels and consonant
int vCount = 0, cCount = 0;
//Declare a string
String str = "My names is Mohamed Abdirizak Ali";
//Converting entire string to lower case to reduce the comparisons
str = str.toLowerCase();
for(int i = 0; i < str.length(); i++) {
//Checks whether a character is a vowel
if(str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') {
//Increments the vowel counter
vCount++;
}
//Checks whether a character is a consonant
else if(str.charAt(i) >= 'a' && str.charAt(i)<='z') {
//Increments the consonant counter
cCount++;
}
}
System.out.println("Number of vowels:" + vCount );
System.out.println("Number of consonants: " + cCount);
scanner.close();
}
}
//OUTPUT:
Number of vowels:12
Number of consonants: 16



Comments