C Programs Tutorials | IT Developer
IT Developer

Java Programs - Advanced



Share with a Friend

Exchange Alphabets Program - Java Program

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 words 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:

Class name: 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.

import java.io.*; class Exchange{ private String sent; private String rev; private int size; public Exchange(){ sent = new String(); rev = new String(); size = 0; } public void readSentence()throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Sentence: "); sent = br.readLine(); sent = sent.trim(); size = sent.length(); } public void exFirstLast(){ String word = new String(); for(int i = 0; i < size; i++){ char ch = sent.charAt(i); if(ch == \' \' || ch == \'.\' || ch == \'?\' || ch == \'!\'){ if(word.length() == 1){ rev += word + " "; word = new String(); } else{ int len = word.length(); char first = word.charAt(0); char last = word.charAt(len - 1); String middle = word.substring(1, len - 1); rev += last + middle + first + " "; word = new String(); } } else word += ch; } rev = rev.trim(); } public void display(){ System.out.println("Original sentence: " + sent); System.out.println("New sentence: " + rev); } public static void main(String args[])throws IOException{ Exchange obj = new Exchange(); obj.readSentence(); obj.exFirstLast(); obj.display(); } }

Output

 
OUTPUT 1:

Sentence: It is a warm day.
Original sentence: It is a warm day.
New sentence: tI si a marw yad


OUTPUT 2:

Sentence: My name is Bharat.
Original sentence: My name is Bharat.
New sentence: yM eamn si tharaB