Write a program to accept a sentence as input. The words in the string are to be separated by a blank. Each word must be in upper case. The...

Write a program to accept a sentence as input. The words in the string are to be separated by a blank. Each word must be in upper case. The sentence is terminated by either '.','!' or '?'. Perform the following tasks:

  1. Obtain the length of the sentence (measured in words)
  2. Arrange the sentence in alphabetical order of the words.

Test your program with the sample data and some random data:

Example 1

 INPUT: NECESSITY IS THE MOTHER OF INVENTION.
 OUTPUT:
 Length: 6
 Rearranged Sentence:
 INVENTION IS MOTHER NECESSITY OF THE

Example 2

 INPUT: BE GOOD TO OTHERS.
 OUTPUT:
 Length: 4
 Rearranged Sentence: BE GOOD OTHERS TO
import java.io.*;
class ISC2012q02
{
public static void main (String args[])throws IOException
{
BufferedReader br=new BufferedReader(
new InputStreamReader (System.in));

int i,j,l,p,x,now;
String str,word,temp;
char ch;

System.out.println("Enter a sentence ");
    str = br.readLine();
    l = str.length();

    now = 0; //To count the  number of words
    for(i=0;i< l;i++){
        ch = str.charAt(i);
        if(ch == ' ' || ch == '?' || ch == '.'
            || ch == '!')
            now++;
    }

    String words[] = new String[now];

    x=0; //Used as index pointer for string array
    p=0; //To store the index of first letter of each word

    for(i=0;i< l;i++){
        ch = str.charAt(i);
        if(ch == ' ' || ch == '?' || ch == '.' 
           || ch == '!'){
            word = str.substring(p,i);
            words[x++] = word;
            p = i+1;
        }
    }

    //Sort the words in string array in alphabetical order

    for(i=1; i< x; i++){
        for(j=0; j< x-i; j++){
            if(words[j].compareTo(words[j+1]) > 0){
                temp = words[j];
                words[j] = words[j+1];
                words[j+1] = temp;
            }
        }
    }

    System.out.println("Length: "+now);
    System.out.println("Rearranged sentence: ");
    for(i=0; i< x; i++){
        System.out.print(words[i]+" ");
    }
}//end of main
}//end of class    

Have something to say? Log in to comment on this post.

0 comments