Question
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 uppercase. The sentence is terminated by either ‘.’, ‘!’ or ‘?’. Perform the following tasks:
Obtain the length of the sentence (measured in words).
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
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
import java.util.StringTokenizer;
public class ArrangeAlphabetically
{
public static void main(String args[])
{
int i=0,j=0,count=0,len=0;
String sen="",temp="",newsen="";
String wd[];
char last=' ';
Scanner sc=new Scanner(System.in);
System.out.print("Sentence: ");
sen =sc.nextLine();
sen = sen.trim();
last = sen.charAt(sen.length() - 1);
if(last != '.' && last != '?' && last != '!')
{
System.out.println("INVALID SENTENCE!");
return;
}
sen = sen.toUpperCase();
StringTokenizer st = new StringTokenizer(sen, " .?!,");
len = st.countTokens();
System.out.println("LENGTH: " + len);
wd = new String[len];
for(i = 0; i < len; i++)
{
wd[i] = st.nextToken();
}
for(i = 0; i < len; i++)
{
for(j = 0; j < len - 1 - i; j++)
{
if(wd[j].compareTo(wd[j + 1]) > 0)
{
temp = wd[j];
wd[j] = wd[j + 1];
wd[j + 1] = temp;
}
}
}
for(i = 0; i < len; i++)
{
newsen += wd[i] + " ";
}
System.out.println("REARRANGED SENTENCE:" + newsen);
}
}
Coding Store
Sale

ISC QUESTION PAPERS WITH SOLUTION(PROGRAMMING ONLY)
Sale

ICSE QUESTION PAPER WITH SOLUTION(PROGRAMMING ONLY)
Sale

ISC QUESTION PAPERS WITH SOLUTION(PROGRAMMING ONLY)
Sale

ICSE QUESTION PAPER WITH SOLUTION(PROGRAMMING ONLY)
Sale

ISC QUESTION PAPERS WITH SOLUTION(PROGRAMMING ONLY)
Sale
