Sort Letters of the Word in Java

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();
    }
}

2 thoughts on “Sort Letters of the Word in Java”

  1. Sir,a program is given which states that:
    WAP in java to accept a decimal number(n>=0) and find its octal and hexadecimal equivalent using recursive function.

    Sample Input:
    N=130
    OCTAL EQUIVALENT:(202)8
    HEXADECIMAL EQUIVALENT:(82)16

    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: