English

A class Sort Alpha has been defined to sort the words in the sentence in alphabetical order.Example: Input: THE SKY IS BLUE Output : BLUE IS SKY THE - Computer Science (Theory)

Advertisements
Advertisements

Question

A class Sort Alpha 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:

Class name Short Alpha

Data members/instance variables:

sent

 to store a sentence

n integer to store the number of
words in a sentence

Methods/Member functions:

ShortAlpha( )

default constructor to initialise data members with legal initial values

void acceptsent( ) to accept a sentence in UPPERCASE
void short(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( ) display the original sentence along with the sorted sentence by invoking the method sort( )

Specify the class Sort Alpha giving details of the constructor (), void acceptsent(), void sort (Sort Alpha) and void display(). Define a main()function to create an object and call the functions accordingly to enable the task.

Answer in Brief

Solution

import java.util. Scanner;
public class SortAlpha
{
   public String sent;
   int n;
   public SortAlpha()
   {
     sent="";
     n=0;
   }
   public void acceptsent()
   {
   Scanner in = new Scanner(System.in);
   System.out.println(“Enter a sentence in Uppercase
   :");
   sent=in.nextLine();
   }
   public void sort(SortAlpha P)
   {
      int i=0,j=0;
      String str=P.sent+" ";
      String word="";
      String words[]=new String[20];
     while (i<str.length())
     {
        if (str.charAt(i)!=' ')
           word+=str.charAt(i);
      else
          {words[j++]=word;
          word="";
          }
      i++;
   }
   int p=j;
for(i= 0; i<p; i++) {
    for(j=0;j<(p- 1-i); j++) {
if (words[j].compareToIgnoreCase(words[j + 1]) >0)
    {
    String temp = words[j + 1];
    words[j + 1] = words[j];
    words[j] = temp;
   }
 }
}
str="";
for (i =0; i<p; i++)
     str+=words[i]+" ";
P.sent=str;
}
public void display()
{
   System.out.println(“Original sentence :"+ sent);
   sort(this);
   System.out.println(“Sorted sentence :"+ sent);
}
    public static void main(String args[])
   {
SortAlpha ob=new SortAlpha();
ob.acceptsent();
ob.display();
}
}
shaalaa.com
Example Algorithms that Use Structured Data Types (E.G. Searching, Finding Maximum/Minimum, Sorting Techniques, Solving Systems of Linear Equations, Substring, Concatenation, Length, Access to Char in String, Etc.)
  Is there an error in this question or solution?
2022-2023 (March) Official
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×