Question : Write the main method in Solution class.
In the main method, read a String (which may have alphabets along with numeric digits) and print the number of vowels and consonants (any alphabet apart from vowel is a consonant) present in the given String. Note: The output should be printed in the same format as mentioned in the sample output.
Consider below sample input and output:
Input: Welcome123
Output: Number of Vowels: 3 Number of Consonants: 4
My Solution:
import java.util.*;
public class MyClass
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
s=s.replaceAll("[^A-Za-z]","");
String v=s.replaceAll("[^AEIOUaeiou]","");
System.out.println("Number of Vowels: " v.length() "\nNumber of Consonants: " (s.length()-v.length()));
}
}
CodePudding user response:
You can use the following which maybe me easier to read, but this wouldn't be the best solution. Your solution is performant and works.
if (consonants.contains(str.charAt(i)))
count ;
}
Never just post your assignment, even if you already have a solution.
CodePudding user response:
You can define a pattern for vowels and consonants as a pattern and don't need to modify the input with replace
You can name your variables better,
You can tidy it up a bit and take care of identation to make it easier to read
Pattern vowel = Pattern.compile("(?i)[aeiou]");
Pattern consonant = Pattern.compile("(?i)([a-z&&[^aeiou]])");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.println("Number of Vowels: " vowel.matcher(input).results().count()
"\nNumber of Consonants: " consonant.matcher(input).results().count());
Note: (?i)
for case insensitive and a-z&&[^aeiou]]
a-z without a,e,i,o,u