‹ Back to the paper
Question 8
10 marks
Computer ScienceISC 2020 Specimen Computer Science Paper 1ProgramObjects
Write the program described below.
Design a class Sort which enables a word to be arranged in alphabetical order. The details of the…
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
Methods/Member functions:
Sort() : default constructor
void readword() : to accept the word
void arrange() : to arrange 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.
Answer
Answer
import java.util.Scanner;
class Sort
{
String str, sw;
int len;
Sort()
{
str = "";
sw = "";
len = 0;
}
void readword()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
str = sc.next();
len = str.length();
}
void arrange()
{
char ch[] = str.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;
}
}
}
sw = new String(ch);
}
void display()
{
System.out.println("Original word : " + str);
System.out.println("Sorted word : " + sw);
}
public static void main(String args[])
{
Sort ob = new Sort();
ob.readword();
ob.arrange();
ob.display();
}
}Explanation: The default constructor sets the words to empty strings and len to 0. readword() accepts the word and stores its length. arrange() copies the characters of the word into an array and sorts them with bubble sort, then stores the sorted characters as a String in an extra data member sw, so that the original word in str is kept and both can be displayed. display() prints the original and the sorted word. Tested: input COMPUTER gives sorted word CEMOPRTU.