Program opened below. You can scroll through the algorithm, Java code and output.
Program 68
Sentence Length and Alphabetical Word Order
Question
Accept an upper-case sentence ending with ., ? or !. Validate the sentence, print the number of words and arrange the words in alphabetical order.
Algorithm
Step 1: Start.
Step 2: Declare the variables and data structures required for the task.
Step 3: Input the sentence and verify its terminator and allowed characters.
Step 4: If invalid, display INVALID SENTENCE and stop.
Step 5: Initialize the counters, flags, accumulators or result structures needed by the solution.
Step 6: Remove the terminator and split the sentence into words.
Step 7: Count the words.
Step 8: Sort the words lexicographically in ascending order.
Step 9: Store the computed result and prepare it for display.
Step 10: Display the count and rearranged sentence.
Step 11: Stop.
Java program
Javaimport java.util.*;
class AlphabeticalWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine().trim();
if (!s.matches("[A-Z]+( [A-Z]+)*[.?!]")) {
System.out.println("INVALID SENTENCE");
return;
}
String body = s.substring(0, s.length() - 1);
String[] words = body.split(" ");
Arrays.sort(words);
System.out.println("LENGTH = " + words.length);
System.out.println("REARRANGED SENTENCE:");
System.out.println(String.join(" ", words));
}
}Sample output
Input: NECESSITY IS THE MOTHER OF INVENTION.
Output:
LENGTH = 6
REARRANGED SENTENCE:
INVENTION IS MOTHER NECESSITY OF THE