javastringcharcounterfrequency

Is there any function that can count with char value?


Write a program to accept a sentence and perform the following tasks:

  1. Count number of vowels and consonants present in each word

  2. Generate the output of the frequency in form of a bar graph, where V denotes vowels and C denotes consonants as shown below:

Example:

INPUT:-

HOW ARE YOU?

OUTPUT:-

WORD COUNT:

HOW
V

CC

ARE
VV

C

YOU
VV

C

The thing I am asking is that how can I print V and C, the number of times the vowels and consonants is occurring.. because I can perform this with digits(like if 2 vowel are there so print 2) but I can't figure that out with char value(here, V and C)

I tried this with for loop with if statement.. but that ain't working

Please help me with this... exams are round the corner


Solution

  • Here is an example.

    Maintain a String for both vowels, and consonants; I'm using a and b.
    Divide the text, s, with the String#split method, and traverse each value.
    From here, increment x by 1 for vowels, and y by 1 for consonants.
    After the loop, print out an occurrence of either "V", or "C", for each x and y, with the String#repeat method.

    String s = "HOW ARE YOU?",
           a = "aeiou", b = "bcdfghjklmnpqrstvwxyz";
    int i, n, x, y;
    char c;
    for (String w : s.split(" +")) {
        System.out.println(w);
        x = y = 0;
        for (i = 0, n = w.length(); i < n; i++) {
            c = Character.toLowerCase(w.charAt(i));
            if (a.indexOf(c) != -1) x++;
            else if (b.indexOf(c) != -1) y++;
        }
        System.out.println("V".repeat(x));
        System.out.println("C".repeat(y));
        System.out.println();
    }
    

    Alternately, utilize the Scanner class to traverse each word.

    Scanner s = new Scanner("HOW ARE YOU?");
    String w, a = "aeiou", b = "bcdfghjklmnpqrstvwxyz";
    int i, n, x, y;
    char c;
    while (s.hasNext()) {
        System.out.println(w = s.next());
        x = y = 0;
        for (i = 0, n = w.length(); i < n; i++) {
            c = Character.toLowerCase(w.charAt(i));
            if (a.indexOf(c) != -1) x++;
            else if (b.indexOf(c) != -1) y++;
        }
        System.out.println("V".repeat(x));
        System.out.println("C".repeat(y));
        System.out.println();
    }
    

    Output

    HOW
    V
    CC
    
    ARE
    VV
    C
    
    YOU?
    VV
    C