Exchange Alphabets ISC Computer Science 2013 Theory
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:
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.
class Exchange{
String sent;
String rev;
int size;
public Exchange(){
sent = new String();
rev = new String();
size = 0;
}
public void readSentence(){
Scanner in = new Scanner(System.in);
System.out.print("Sentence: ");
sent = in.nextLine();
size = sent.length();
char last = sent.charAt(size - 1);
if(last != '.' || sent.indexOf(" ") >= 0){
System.out.println("INVALID INPUT");
System.exit(0);
}
}
public void exFirstLast(){
String word = new String();
for(int i = 0; i < size; i++){
char ch = sent.charAt(i);
if(Character.isLetterOrDigit(ch))
word += ch;
else if(word.length() == 1){
rev += word + ch;
word = new String();
}
else if(word.length() > 1){
int len = word.length();
char first = word.charAt(0);
char last = word.charAt(len - 1);
rev += last + word.substring(1, len - 1) + first + ch;
word = new String();
}
else
rev += ch;
}
}
public void display(){
System.out.println("Original sentence: " + sent);
System.out.println("Changed sentence: " + rev);
}
public static void main(String[] args) {
Exchange obj = new Exchange();
obj.readSentence();
obj.exFirstLast();
obj.display();
}
}
Comments
Post a Comment