Java program to arrange sentences in a Paragraph in Ascending order of their Number of words
Java program to input a paragraph of text and arrange the sentences in it in increasing order of their number of words.
Question:
Accept a paragraph of text consisting of sentences that are terminated by either '.' (full stop), '!' (exclamation mark) or a '?' (question mark). Assume that there can be maximum 10 sentences in a paragraph. Write a program to arrange the sentences in increasing order of their number of words.
Example :
INPUT : Please come and attend the party. Hello! How are you?
OUTPUT :
Hello = 1
How are you = 3
Please come and attend the party = 6
Programming Code:
Java
/**
* The class sortParagraph inputs a paragraph and arranges the
* sentences in ascending order of their number of words
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
*/
import java.util.*;
class sortParagraph
{
// Function to count no. of words in every sentence
int countWords(String s)
{
StringTokenizer str = new StringTokenizer(s," .,?!");
int c = str.countTokens();
return c;
}
// Function to sort the sentences in ascending order of their no. of words
void sort(String w[], int p[])
{
int n = w.length, t1 = 0;
String t2 = "";
for(int i=0; i<n-1; i++)
{
for(int j=i+1; j<n; j++)
{
if(p[i]>p[j]) // for descending use p[i]<p[j]
{
t1 = p[i];
p[i] = p[j];
p[j] = t1;
t2 = w[i];
w[i] = w[j];
w[j] = t2;
}
}
}
printResult(w,p); // Calling function for printing the result
}
void printResult(String w[], int p[]) // Function to print the final result
{
int n = w.length;
for(int i=0; i<n; i++)
{
System.out.println(w[i]+"\t=\t"+p[i]);
}
}
public static void main(String args[])
{
sortParagraph ob = new sortParagraph();
Scanner sc = new Scanner(System.in);
System.out.print("Enter a paragraph : "); //Inputting a paragraph
String pg = sc.nextLine();
StringTokenizer str = new StringTokenizer(pg,".?!");
int count = str.countTokens(); //Counting no. of sentences in the paragraph
if(count > 10)
System.out.println("A maximum of 10 sentences are allowed in the paragraph");
else
{
String sent[] = new String[count]; //Array to store the sentences separately
int p[] = new int[count]; //Array to store no. of words of each sentence
for(int i=0; i<count; i++)
{
sent[i] = str.nextToken().trim(); // Saving sentences one by one in an array
p[i] = ob.countWords(sent[i]); // Saving no. of words of every sentence
}
ob.sort(sent,p);
}
}
}Output:
Enter a paragraph : Please come and attend the party. Hello! How are you?
OUTPUT :
Hello = 1
How are you = 3
Please come and attend the party = 6