Java – How to Detect the Vowels and Consonants in the program

java

    String text;
    System.out.print ("Enter a String:");
    text = console.nextLine();

    int spaces = 0;
    int consonants = 0;
    int vowelcount = 0 ;

    for (int index = 0; index < text.length(); index++) {
    char letters = text.charAt(index);


    if (letters == 'A' || letters == 'a')
        vowelcount++;



    else if (letters != 'a' && letters != 'e' && letters != 'i' && letters != 'o' && letters != 'u')
        consonants++;

    }


        System.out.println ("Vowels:" + vowelcount  + "\nConsonants :" + consonants + "\nSpaces : " + spaces);

Sample Output
String: Hannah
Last Portion of Output
Vowels Detected: a a
Consonants Detected: h n n h

Best Answer

Here are a couple help methods

public static boolean isVowel(char c){
    String vowels = "aeiouAEIOU";
    return vowels.contains(c);
}

public static boolean isConsanant(char c){
    String cons = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
    return cons.contains(c);
}

Use them here

char c = line.charAt(i);
int vowelCount = 0;
int consanantCount = 0;
int space = 0;
int punctuation = 0;

if (isVowel(c))
    vowelCount++;
else if (isConsanant(c))
    consanantCount++;
else if (Character.isWhitepace(c))
    space++;
else
    punctuation++;