Vowels Consonants ISC 2015 Practical

Write a program to accept a sentence which may be terminated by either ‘.’ or ‘?’ only. The words are to be separated by a single blank space. Print an error message if the input does not terminate with ‘.’ or ‘?’. You can assume that no word in the sentence exceeds 15 characters, so that you get a proper formatted output.

Perform the following tasks:
(i) Convert the first letter of each word to uppercase.
(ii) Find the number of vowels and consonants in each word and display them with proper headings along with the words.

Test your program with the following inputs:

Example 1:
INPUT: Intelligence plus character is education.
OUTPUT:
Intelligence Plus Character Is Education.

Word            Vowels        Consonants
Intelligence 5 7
Plus 1 3
Character 3 6
Is 1 1
Education 5 4

Example 2:
INPUT: God is great.
OUTPUT:
God is great.

Word        Vowels        Consonants
God 1 2
Is 1 1
Great 2 3

Example 3:
INPUT: All the best!
OUTPUT:
Invalid input.

import java.io.*;
class Title{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("String: ");
        String s = br.readLine();
        s = s.trim();
        int len = s.length();
        char last = s.charAt(len - 1);
        if(last != '.' && last != '?'){
            System.out.println("Invalid input.");
            return;
        }
        String t = new String();
        for(int i = 0; i < len; i++){
            char ch = s.charAt(i);
            if(i == 0)
                t += Character.toUpperCase(ch);
            else if(ch == ' '){
                t += " " + Character.toUpperCase(s.charAt(i + 1));
                i++;
            }
            else
                t += Character.toLowerCase(s.charAt(i));
        }
        System.out.println(t);
        System.out.println("Word\t\tVowels\t\tConsonants");
        String word = new String();
        for(int i = 0; i < len; i++){
            char ch = s.charAt(i);
            if(ch == ' ' || ch == '.' || ch == '?'){
                display(word);
                word = new String();
            }
            else
                word += ch;
        }
    }
    public static void display(String w){
        int v = 0;
        int c = 0;
        w = w.toUpperCase();
        for(int i = 0; i < w.length(); i++){
            char ch = w.charAt(i);
            switch(ch){
                case 'A':
                case 'E':
                case 'I':
                case 'O':
                case 'U':
                v++;
                break;
                default:
                c++;
            }
        }
        System.out.printf("%-16s%-16d%-16d\n", w, v, c);
    }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.