Home > Software design >  Count Vowels and Consonants
Count Vowels and Consonants

Time:03-30

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);
    }
}

CodePudding user response:

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

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

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

CodePudding user response:

The comparison of characters the way it is done can create confusion, as you can see from 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