Swap Sort Java Program ISC 2017

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 the 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 uppercase.
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, swapped word and sorted word.
void display(): displays the original word, swapped word and the sorted word.

Specify the class SwapWord, giving 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.

import java.io.*;
class SwapSort{
    private String wrd;
    private int len;
    private String swapwrd;
    private String sortwrd;
    public SwapSort(){
        wrd = "";
        swapwrd = "";
        sortwrd = "";
        len = 0;
    }
    public void readWord()throws IOException{
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);
        System.out.print("Word = ");
        wrd = br.readLine();
        wrd = wrd.trim();
        if(wrd.indexOf(' ') > 0)
            wrd = wrd.substring(0, wrd.indexOf(' '));
        wrd = wrd.toUpperCase();
        len = wrd.length();
    }
    public void swapChar(){
        char first = wrd.charAt(0);
        char last = wrd.charAt(len - 1);
        if(len == 1)
            swapwrd = wrd;
        else if(len == 2)
            swapwrd += last + first;
        swapwrd = last + wrd.substring(1, len - 1) + first;
    }
    public void sortWord(){
        char a[] = new char[len];
        for(int i = 0; i < len; i++)
            a[i] = wrd.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;
                }
            }
        }
        for(int i = 0; i < len; i++)
            sortwrd += a[i];
    }
    public void display(){
        System.out.println("Swapped word: " + swapwrd);
        System.out.println("Sorted word: " + sortwrd);
    }
    public static void main(String args[])
    throws IOException{
        SwapSort obj = new SwapSort();
        obj.readWord();
        obj.swapChar();
        obj.sortWord();
        obj.display();
    }
}

Leave a Reply