Question
A class SwapSort has been defined to perform string related operations on a word input. Some of the members of the class are as follows:
Class name SwapSort
Data members/instance variables:
wrd:to store a word
len:integer to store length of the word
swapwrd: to store the swapped word
sortwrd:to store the sorted word
Member functions/methods:
SwapSort( ):default constructor to initialize data members with legal initial values
void readword( ):to accept a word in UPPER CASE
void swapchar( ):to interchange/swap the first and last characters of the word in ‘wrd’ and stores the new word in ‘swapwrd’
void sortword( ):sorts the characters of the original word in alphabetical order and stores it in ‘sortwrd’
void display( )displays the original word, swapped word and the sorted word
Specify the class SwapSort, giving the details of the constructor( ), void readword( ), void swapchar( ), void sortword( ) 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 SwapSort
{
String wrd,swapwrd,sortwrd;
int len;
Scanner sc=new Scanner(System.in) ;
SwapSort()
{
swapwrd="" ;
sortwrd=" ";
len=0;
wrd="";
}
void readword()
{
System.out.println("Enter word in Upper case");
wrd=sc.next() ;
len=wrd.length();
wrd=wrd.toUpperCase();
}
void swapchar()
{
/*add last character of word to swapwrd*/
swapwrd=swapwrd+wrd.charAt(len-1);
/*add characters between first and last character of word to swapwrd*/
swapwrd=swapwrd+ wrd.substring(1,len-1);
/*add first character to swapwrd*/
swapwrd=swapwrd + wrd.charAt(0);
}
void sortword()
{
char ch1;
for(char ch='A' ;ch<='Z';ch++)
{
for(int i=0 ;i < len;i++)
{
ch1=wrd.charAt(i);
if(ch1==ch)
{
sortwrd += ch1;
}
}
}
}
void display()
{
System.out.println("Original word = " + wrd);
System.out.println("Swapped word = " + swapwrd);
System.out.println("Sorted word = " + sortwrd);
}
public static void main()
{
SwapSort ob1=new SwapSort();
ob1.readword() ;
ob1.swapchar();
ob1.sortword();
ob1.display();
}
}