‹ Back to the paper
A class SortAlpha has been defined to sort the words in the sentence in alphabetical order…
A class SortAlpha has been defined to sort the words in the sentence in alphabetical order.
Example:
Input: THE SKY IS BLUE
Output: BLUE IS SKY THE
Some of the members of the class are given below:
Specify the class SortAlpha giving details of the constructor( ), void acceptsent( ), void sort(SortAlpha) and void display(). Define a main() function to create an object and call the functions accordingly to enable the task.
| Class name | : | SortAlpha |
|---|---|---|
| **Data members/instance variables:** | ||
| sent | : | to store a sentence |
| n | : | integer to store the number of words in a sentence |
| **Methods / Member functions:** | ||
| SortAlpha( ) | : | default constructor to initialise data members with legal initial values |
| void acceptsent( ) | : | to accept a sentence in UPPER CASE |
| void sort(SortAlpha P) | : | sorts the words of the sentence of object P in alphabetical order and stores the sorted sentence in the current object |
| void display( ) | : | displays the original sentence along with the sorted sentence by invoking the method sort() |
Answer
Answer
AIimport java.util.Scanner;
class SortAlpha
{
String sent; // the sentence
int n; // number of words in the sentence
// default constructor
SortAlpha()
{
sent = "";
n = 0;
}
// accepts a sentence in upper case and counts its words
void acceptsent()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence in UPPER CASE: ");
sent = sc.nextLine().trim().toUpperCase();
n = sent.split("\\s+").length;
}
// sorts the words of P's sentence alphabetically and stores the result in this object
void sort(SortAlpha P)
{
String w[] = P.sent.split("\\s+");
int len = w.length;
// bubble sort on the words
for (int i = 0; i < len - 1; i++)
{
for (int j = 0; j < len - 1 - i; j++)
{
if (w[j].compareTo(w[j + 1]) > 0)
{
String t = w[j];
w[j] = w[j + 1];
w[j + 1] = t;
}
}
}
sent = "";
for (int i = 0; i < len; i++)
sent = sent + w[i] + " ";
sent = sent.trim();
n = len;
}
// displays the original sentence and the sorted sentence
void display()
{
SortAlpha ob = new SortAlpha();
ob.sort(this);
System.out.println("Original sentence: " + sent);
System.out.println("Sorted sentence: " + ob.sent);
}
public static void main(String args[])
{
SortAlpha obj = new SortAlpha();
obj.acceptsent();
obj.display();
}
}sort() splits the sentence of object P into words, arranges them with bubble sort using compareTo(), and joins them back into the current object's sent. display() creates a second object, calls sort(this) on it so the original sentence is kept unchanged, and prints both.
Sample run:Enter a sentence in UPPER CASE: THE SKY IS BLUE
Original sentence: THE SKY IS BLUE
Sorted sentence: BLUE IS SKY THEFrom ISC 2023 Computer Science Paper 1, question 8.