‹ Back to the paper
A class SwapSort has been defined to perform string related operations on a word input. Some of the…
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.
Answer
Answer
AIimport java.util.Scanner;
class SwapSort
{
String wrd, swapwrd, sortwrd;
int len;
SwapSort()
{
wrd = "";
swapwrd = "";
sortwrd = "";
len = 0;
}
void readword()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word in UPPER CASE: ");
wrd = sc.next();
len = wrd.length();
}
void swapchar()
{
if (len > 1)
swapwrd = wrd.charAt(len - 1) + wrd.substring(1, len - 1) + wrd.charAt(0);
else
swapwrd = wrd;
}
void sortword()
{
char ch[] = wrd.toCharArray();
for (int i = 0; i < len - 1; i++)
{
for (int j = 0; j < len - 1 - i; j++)
{
if (ch[j] > ch[j + 1])
{
char t = ch[j];
ch[j] = ch[j + 1];
ch[j + 1] = t;
}
}
}
sortwrd = new String(ch);
}
void display()
{
System.out.println("Original word : " + wrd);
System.out.println("Swapped word : " + swapwrd);
System.out.println("Sorted word : " + sortwrd);
}
public static void main(String args[])
{
SwapSort obj = new SwapSort();
obj.readword();
obj.swapchar();
obj.sortword();
obj.display();
}
}Explanation: swapchar() builds the new word as last character + middle part + first character. sortword() copies the word into a char array and sorts it with bubble sort, then stores it as a String in sortwrd. Tested by running: input HELLO gives swapped word OELLH and sorted word EHLLO.From ISC 2017 Computer Science Paper 1, question 9.