C Programs Tutorials | IT Developer
IT Developer

Java Programs - Advanced



Share with a Friend

Sort Words Alphabetically Program - Java Program

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:

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 initialize data members with legal initial values
void acceptsent(): to accept a sentence in uppercase
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()

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.

import java.util.Scanner; class SortAlpha{ String sent; int n; public SortAlpha(){ sent = ""; n = 0; } public void acceptsent(){ Scanner in = new Scanner(System.in); System.out.print("Enter the sentence: "); sent = in.nextLine().trim().toUpperCase(); if(sent.length() > 0){ n = 1; for(int i = 1; i < sent.length(); i++){ char ch = sent.charAt(i); if(Character.isWhitespace(ch)) n++; } } else n = 0; } public void sort(SortAlpha P){ String words[] = new String[P.n]; int index = 0; String word = ""; P.sent += " "; for(int i = 0; i < P.sent.length(); i++){ char ch = P.sent.charAt(i); if(Character.isWhitespace(ch)){ words[index++] = word; word = ""; } else if(Character.isLetterOrDigit(ch)) word += ch; } for(int i = 0; i < words.length; i++){ for(int j = 0; j < words.length - 1 - i; j++){ if(words[j].compareTo(words[j + 1]) > 0){ String temp = words[j]; words[j] = words[j + 1]; words[j + 1] = temp; } } } for(int i = 0; i < words.length; i++) sent += words[i] + " "; } public void display(){ System.out.println(sent); } public static void main(String[] args){ SortAlpha obj1 = new SortAlpha(); SortAlpha obj2 = new SortAlpha(); obj1.acceptsent(); obj2.sort(obj1); obj2.display(); } }

Output

 

OUTPUT :

Enter the sentence: THE SKY IS BLUE
BLUE IS SKY THE