icse-promo

Question

Design a class Exchange to accept a sentence and interchange the first alphabet with the last
alphabet for each word in the sentence,with single letter word remaining unchanged. The words in the input sentence are separated by a single blank space and terminated by a full stop.
Example: Input: It is a warm day.
Output: tI si a marw yad
Some of the data members and member functions are given below:

Classname:Exchange
Data members / instance variables:

sent:stores the sentence
rev:to store the new sentence
size: stores the length of the sentence

Member functions:

Exchange(): default constructor
void readsentence():to accept the sentence

void exfirstlast():extract each word and interchange the first and last alphabet of the word and form a new sentence rev using the changed words

void display():display the original sentence along with the new changed sentence.

Specify the class Exchange giving details of the constructor(), void readsentence() , void exfirstlast() and void display(). Define the main() function to create an object and call the functions accordingly to enable the task.

 

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;
public class Exchange
{
    String sent,rev;
    int size;
    Exchange()
    {
        sent="";
        rev="";
        size=0;
    }

    void readsentence()
    {
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter a sentence");
        sent=sc.nextLine();
        size=sent.length();
    }
    
    void exfirstlast()
    {
        char ch=' ';
        String wd="";
        for(int i=0;i< size;i++)
        {    
            ch=sent.charAt(i);
            if(ch==' '||ch=='.')
            { 
                if(wd.length()>1)
                {
                    /*last character*/
                    rev=rev + wd.charAt(wd.length()-1);
                    /*middle characters*/
                    rev=rev + wd.substring(1,wd.length()-1);
                    /*first character*/
                    rev=rev + wd.charAt(0);
                    /*space or full stop*/
                    rev=rev+ch;
                }
                else
                {
                    rev=rev+wd+ch;
                }

                wd="";
            }
            else
            {
                wd=wd+ch;
            }
        }
    }

    void display()
    {
        System.out.println("Input:"+sent);
        System.out.println("Output: "+rev);
    }

    public static void main()
    {
        Exchange obj1=new Exchange();
        obj1.readsentence();
        obj1.exfirstlast();
        obj1.display();
    }
}



				
			

Coding Store

Leave a Reply

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