A class SwapSort has been defined to string related manipulations on a input word.
Some of the members of the class are as follows
wrd: To store the word
len: length of the word
swapwrd: to store the swapped word
sortwrd: to store the sorted word
SwapSort(): default constructor ti initialize the members with valid value
void readWord(): accept the word in upper case
void sortWord(): sort the word in ascending order and stores in sortwrd
void swapChar(): Exchange the first and last character of the word and stores in swapwrd
void display (): Display all the words (original, swapped and sorted
import java.util.*;
public class SwapSort
{
String wrd, swapwrd, sortwrd;
int len;
Scanner sc=new Scanner(System.in);
SwapSort()
{
wrd="";
sortwrd="";
swapwrd="";
len=0;
}
void readWord()
{
System.out.print("\nEnter the word: ");
wrd=sc.nextLine().toUpperCase();
}
void swapChar()
{
len=wrd.length();
System.out.println(wrd.charAt(len-1));
swapwrd=swapwrd+wrd.charAt(len-1);
for(int i=1;i<len-1;i++)
swapwrd=swapwrd+wrd.charAt(i);
swapwrd=swapwrd+wrd.charAt(0);
}
void sortWord()
{
char c;
char ch[]=new char[len];
for(int i=0;i<len;i++)
ch[i]=wrd.charAt(i);
for(int i=0;i<len-1;i++)
{
for(int j=i+1;j<len;j++)
{
if(ch[i]>ch[j])
{
c=ch[i];
ch[i]=ch[j];
ch[j]=c;
}
}
}
sortwrd=new String(ch);
}
void display()
{
System.out.println("\nOriginal Word:"+wrd);
System.out.println("\nSorted Word:"+sortwrd);
System.out.println("\nSwapped Word:"+swapwrd);
}
public static void main(String[] args)
{
SwapSort ob=new SwapSort();
ob.readWord();
ob.swapChar();
ob.sortWord();
ob.display();
}
}
No comments:
Post a Comment