C Programs Tutorials | IT Developer
IT Developer

Java Programs - Advanced



Share with a Friend

Bar Graph of Vowels & Consonants Program - Java Program

Write a program to accept a sentence which may be terminated by either ‘.’, ‘?’ or ‘!’ only. The words may be separated by single blank spaces and are in uppercase.

Perform the following tasks:
(a) Count number of vowels and consonants present in each word.
(b) Generate the output of the frequency in the form of a bar graph, where V denotes vowels and C consonants, as shown below.

Test your program for the following data and some random data:

Example 1
INPUT: HOW ARE YOU?
OUTPUT:

WORD        COUNT

HOW         V

            CC

ARE         VV

            C

YOU         VV

            C

 

Example 2
INPUT: GOOD DAY!
OUTPUT:

WORD        COUNT

GOOD        VV

            CC

DAY         V

            CC

 

Example 3
INPUT: LONG LIVE THE KING#
OUTPUT: INCORRECT TERMINATING CHARACTER. INVALID INPUT

 

import java.util.Scanner; class BarGraph{ public static void main(String[] args){ Scanner in = new Scanner(System.in); System.out.print("Enter the sentence: "); String s = in.nextLine().toUpperCase(); char last = s.charAt(s.length() - 1); if(".?!".indexOf(last) == -1){ System.out.println("INCORRECT TERMINATING CHARACTER. INVALID INPUT"); return; } System.out.println("WORD\tCOUNT"); String word = ""; int v = 0; int c = 0; for(int i = 0; i < s.length(); i++){ char ch = s.charAt(i); if(Character.isLetterOrDigit(ch)){ word += ch; if("AEIOU".indexOf(ch) >= 0) v++; else c++; } else{ System.out.print(word + "\t"); for(int j = 1; j <= v; j++) System.out.print("V"); System.out.print("\n\t"); for(int j = 1; j <= c; j++) System.out.print("C"); System.out.println(); v = 0; c = 0; word = ""; } } } }

Output

 
OUTPUT 1:
Enter the sentence: HOW ARE YOU?
WORD    COUNT
HOW V
    CC
ARE VV
    C
YOU VV
    C

OUTPUT 2:

Enter the sentence: GOOD DAY!
WORD    COUNT
GOOD    VV
    CC
DAY V
    CC

OUTPUT 3:

Enter the sentence: LONG LIVE THE KING#
INCORRECT TERMINATING CHARACTER. INVALID INPUT