String based Java Program

Q. Write a menu driven program to generate a string. (i.e., Choice: 1 First letter of all the words & Choice: 2 Last letter of all the words) from a sentence given by the user. Count the number of vowel present in the string.

Sample Input:

THANK YOU TO ALL THE COVID WARRIORS FOR SAVING OUR LIVES.

Enter your choice: 1

Output: TYTATCWFSOL

Total vowels=2

Enter your choice: 2

Output: KUOLEDSRGRS

Total vowels=3

import java.io.*;
class Abc
{
    public static void main(String args[])throws IOException
    {
        //Input
        BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
        System.out.println("Enter a Sentence.");
        String s=br.readLine();
        
        //separate out the words from Sentence
        String word[] = new String[20];
        int x=0, z=0;
        for(int i=0; i<s.length(); i++)
        {
            char ch=s.charAt(i);
            if(ch==' ' || ch=='.')
            {
                word[x++]=s.substring(z, i);
                z=i+1;
            }
        }
        
        //User's choice
        System.out.println("Enter your choice"
                           + "\n1: First letter of all the words"
                           + "\n2: Last letter of all the words");
        int choice = Integer.parseInt(br.readLine());
        
        String f="";
        switch(choice)
        {
            case 1: for(int i=0; i<x; i++)
                        f=f+word[i].charAt(0);
                    break;
            case 2: for(int i=0; i<x; i++)
                        f=f+word[i].charAt(word[i].length()-1);
                    break;
            default: System.out.println("Wrong Choice");
                    break;
        }
        
        System.out.println("Output: " +f);
        
        int a=0;
        for(int i=0; i<f.length(); i++)
        {
            char ch = f.charAt(i);
            if(ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U')
                a++;
        }
        System.out.println("Total no. of vowels = " + a);
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *