Search code examples
javastringfunctionbluej

counting the number of consonants in a string


My objective is to count the number of consonants ONLY, in a String,and this is my code:

import java.io.*;
/**
 * Write a description of class Program46 here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class Program46
{
    public static void main()throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter phrase: ");
        String phrase=br.readLine();
        int lth=phrase.length();
        int ctr=0;
        for(int i=0;i<=lth-1;i++)
        {
            char a=phrase.charAt(i);
            boolean chk=Character.isDigit(a);
            if(a!='a'&&a!='e'&&a!='i'&&a=='o'&&a!='u'&&a!=' '&& chk==false)
                ctr++;

        }
        System.out.println("No. of consonents: "+ctr);
    }
}

The program does compile,showing no syntax error. However,when I execute this in void main(), no matter what I input,the number of consonants it counts is always 0. Is there any error in my program? If so,I request you suggest a better way to do this,or a way to correct the above code.


Solution

  • There are two things wrong with your code:

    1. You have a typo when checking for the vowel 'o'. Instead of a == 'o', it should be a != 'o'
    2. Even if you fix this, your check only considers LOWER CASE vowels, a space character, and numbers. If the character being checked is not anyone of these then it'll be counted as a consonant. That includes UPPER CASE vowels, special characters (!@#$ etc...), other space characters ('\t'), and punctuation.

    The corrections could something like:

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter phrase: ");
        String phrase = br.readLine();
        int lth = phrase.length();
        int ctr = 0;
        for (int i = 0; i <= lth - 1; i++) {
            char ch = phrase.charAt(i);
            // Skip this character if it's not a letter
            if (!Character.isLetter(ch)) {
                continue;
            }
    
            if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u' &&
                ch != 'A' && ch != 'E' && ch != 'I' && ch != 'O' && ch != 'U' ) {
                ctr++;
            }
        }
        System.out.println("No. of consonents: " + ctr);
    }
    

    Once you reach this point, you can look into ways of "improving" the code.