Count Vowels and Consonants

Viewed 94

I was exploring this code which gives a count of vowels and consonants, but didn't understand this else if (ch >= 'a' && ch <= 'z') line of code. Please tell me what's the logic behind it.

import java.util.Scanner;

public class Vowels {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter string");
        String str = sc.nextLine();
        int vowl = 0;
        int conso = 0;

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                vowl++;
            } else if (ch >= 'a' && ch <= 'z') {
                conso++;
            }
        }
        System.out.println(vowl);
        System.out.println(conso);
    }
}
4 Answers

A benefit of chars is that you can operate with them like if they were integers.

For example, you can do you this as well 'a' + 3 = 'd'

Meaning that 'a' < 'd' = true.

The comparison of characters the way it is done can create confusion, as you can see from Java: Character comparison.

Basically @TDG is correct by saying that ch is checked to be between 'a' and 'z', and thus the check might be translated as "is ch a lower case character?"

The tricky part is that depending on the language people use the expectation can be different, especially since language specific characters are not taken into account. In German language, 'ö' would definitely qualify as lower case character but is not in the range of the check. The complexity may get evident by studying the Unicode code charts.

The best check is to use Character.isLowerCase().

char is a character that represented by a number which is the index of the character in the ASCII/unicode table, since the the alphabet characters are arranged in order in the ASCII table, the following code checks if the ch is in the range of the lowercase alphabet characters representation which is 97 to 122 in the table.

using (int) ch you can see the decimal value of the character and can compare it with the index in the ASCII table.

you can see the ASCII table here:https://www.asciitable.com/

enter image description here

  • notice the if statement catches all vowels

  • whats ever is not a vowel will either be a capital letter, a number, a special character or consonants

    else if (ch >= 'a' && ch <= 'z')
    this checks if its not a vowel does it atleast fall in the range of small letter 'a'-'z' and is not a special charecter or a number.( we knonw its not a vowel but is it in the ascii range 26=a -51=z)

refer to the ASCII table to understand the range comparison

Related