Programming Examples

Java program to count the number of vowel and consonants in each word of sentence


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.

Solution

import java.util.*;
class Count
{
	public static void main(String arr[])
	{
		String str,str1="",word="";
		int vowel=0,conso=0;
		Scanner sc=new Scanner(System.in);
		System.out.println("Enter any String");
		str=sc.nextLine();
		if(!(str.endsWith(".")||str.endsWith("?")))
		{
			System.out.println("Invalid Input");
			System.exit(0);
		}
		else
		{
			str=str.substring(0,str.length()-1);
			
			for (int a=0;a<str.length();a++)
			{
				if(str.charAt(a)==' ')
				{
					str1=str1+' '+Character.toUpperCase(str.charAt(a+1));
					a++;
					continue;
				}
				str1=str1+str.charAt(a);
			}
			str=str1;
			System.out.println(str);
		}
		System.out.println("Word\tVowels\tConsonants");
		for (int a=0;a<str.length();a++)
		{
			if(str.charAt(a)==' ')
			{
			
				System.out.println(word+"\t"+vowel+"\t"+conso);
				vowel=0;
				conso=0;
				word="";
			}
			else
			{
				char ch=Character.toLowerCase(str.charAt(a));
				if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
				{
					vowel++;
				}
				else
				{
					conso++;
				}
				word=word+str.charAt(a);
			}
		}
		System.out.println(word+"\t"+vowel+"\t"+conso);
	}
}
	
Output

Enter any String

ram is a good boy.

ram Is A Good Boy

Word    Vowels  Consonants

ram     1       2

Is      1       1

A       1       0

Good    2       2

Boy     1     2

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz