Design a class Sort which enables a word to be arranged in alphabetical order. The details of the members of the class are given below :
Class name: Sort
Data members/instance variables:
str: stores a word.
len: to store the length of the word.
Member functions:
Sort( ): default constructor.
void readWord( ): to accept the word.
void arrange( ): to arrange the letters of the word in alphabetical order using any standard sorting technique.
void display( ): displays the original word along with the sorted word.
Specify the class Sort giving details of the constructor, void readword( ), void arrange( ), and void display(). Define the main( ) function to create an object and call the functions accordingly to enable the task.
import java.io.*;
class Sort{
String str;
int len;
public Sort(){
str = "";
len = 0;
}
public void readWord()throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the word: ");
str = br.readLine();
str = str.trim();
if(str.indexOf(' ') > 0)
str = str.substring(0, str.indexOf(' '));
len = str.length();
}
public void arrange(){
char a[] = new char[len];
for(int i = 0; i < len; i++)
a[i] = str.charAt(i);
for(int i = 0; i < len; i++){
for(int j = 0; j < len - 1 - i; j++){
if(a[j] > a[j + 1]){
char temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
str = "";
for(int i = 0; i < len; i++)
str += a[i];
}
public void display(){
System.out.println("Original word: " + str);
arrange();
System.out.println("Sorted word: " + str);
}
public static void main(String args[])throws IOException{
Sort obj = new Sort();
obj.readWord();
obj.display();
}
}