We are uploading our contents, please refresh app.
Java Premium

write a program in Java to input a line to Count the Number of vowels, consonants, digits and spaces in a given sentence

In this program, you'll learn to count the number of vowels, consonants, digits and spaces in a given sentence using if else in Java.


Program:
import java.util.*;
public class Count 
{
 public static void main(String[] args) {
        String line;
        int vowels = 0, consonants = 0, digits = 0, spaces = 0;
        Scanner sc=new Scanner(System.in);
        System.out.println("Input a line: ");
        line=sc.nextLine();
        line = line.toLowerCase();
        for(int i = 0; i < line.length(); ++i)
        {
            char ch = line.charAt(i);
            if(ch == 'a' || ch == 'e' || ch == 'i'
                || ch == 'o' || ch == 'u') {
                ++vowels;
            }
            else if((ch >= 'a'&& ch <= 'z')) {
                ++consonants;
            }
            else if( ch >= '0' && ch <= '9')
            {
                ++digits;
            }
            else if (ch ==' ')
            {
                ++spaces;
            }
        }
        System.out.println("Vowels: " + vowels);
        System.out.println("Consonants: " + consonants);
        System.out.println("Digits: " + digits);
        System.out.println("White spaces: " + spaces);
    }
}
Output:
Input a line: 
welcome to java 2020

Vowels: 6
Consonants: 7
Digits: 4
White spaces: 3

In the above example, we've 4 conditions for each of the checks.

  1. The first if condition is to check whether the character is a vowel or not.
  2. The else if condition following if is to check whether the character is a consonant or not. The order should be the same otherwise, all vowels are treated as consonants as well.
  3. The 3rd condition (else-if) is to check whether the character is between 0 to 9 or not.
  4. Finally, the last condition is to check whether the character is a space character or not.
  5. For this, we've lowercased the line using toLowerCase(). This is an optimization done not to check for capitalized A to Z and vowels.
  6. We've used length() function to know the length of the string and charAt() to get the character at the given index (position).

Online user

Download our android app Download App Submit your query
x

Get Updates On

Java & Premium Programs

Java Solved & Questions

Java Coding easy to use

Proper Coding

Straight Into Your INBOX!

We are going to send you our resources for free. To collect your copy at first, join our mailing list. We are promising not to bother you by sending useless information. So don't miss any updates, stay connected!