ISC Computer Practical 2015 Question 3

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 character, 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

The Java implementation forΒ ISC Computer Practical 2015 Question 3 problem is as follows:

import java.util.*;
class Q3{
    public static boolean isVowel( char ch ){
        String vowel="aeiouAEIOU";
        return vowel.indexOf(ch)>=0;
    }
    public static boolean isConsonant( char ch ){
        return Character.isLetter(ch) && !isVowel(ch);
    }
    public static void main( String args[] ){
        Scanner sc = new Scanner( System.in );
        System.out.print( "INPUT: ");
        String input = sc.nextLine();
        char ch=input.charAt(input.length()-1);
        if( ch!='.' && ch!='?'){
            System.out.println("OUTPUT:Invalid Input");
        }else{
            input=input+" ";
            String word="";
            int vowels=0, consonants=0;
            String ans="",out=String.format("%-16s\t%s\t%s\n","Word","Vowels","Consonants");
            for( int i=0; i<input.length()-1;i++ ){
                ch=input.charAt(i);
                if(ch==' ' || ch==',' || ch=='?' || ch=='.' || ch==';' ){
                    out+=String.format("%-16s\t%2d\t%2d\n",word,vowels,consonants);
                    ans=ans+word+ " ";
                    word="";
                    vowels=consonants=0;
                }else{
                    if(isVowel(ch)) vowels++;
                    if(isConsonant(ch)) consonants++;
                    if(word.equals("")) ch=Character.toUpperCase(ch);
                    word = word+ch;
                }
            }
            ans=ans.trim();
            System.out.println("OUTPUT:\n"+ans+"\n"+out);
        }
    }
}

Note that the function isConsonant( ) checks for not vowel as well as for a letter. Also note the use of String.format to get a properly formatted output. The above program uses only basic string manipulation and one loop which results in increased efficiency.