Arrange Words ISC Computer Science 2020 Practical
Write a program to accept a sentence which may be terminated by either '.', '?' or '!' only. The words are to be separated by a single blank space and are in uppercase.
Perform the following tasks:
(a) Check for the validity of the accepted sentence only for the terminating character.
(b) Arrange the words in ascending order of their length. If two or more words have the same length, then sort them alphabetically.
(c) Display the original sentence along with the converted sentence.
Test your program for the following data and some random data:
Example 1:
INPUT:
AS YOU SOW SO SHALL YOU REAP.
OUTPUT:
AS YOU SOW SO SHALL YOU REAP.
AS SO SOW YOU YOU REAP SHALL
Example 2:
INPUT:
SELF HELP IS THE BEST HELP.
OUTPUT:
SELF HELP IS THE BEST HELP.
IS THE BEST HELP HELP SELF
Example 3:
INPUT:
BE KIND TO OTHERS.
OUTPUT:
BE KIND TO OTHERS.
BE TO KIND OTHERS
Example 4:
INPUT:
NOTHING IS IMPOSSIBLE#
OUTPUT:
INVALID INPUT
import java.util.StringTokenizer;
class Arrange{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter the sentence: ");
String s = in.nextLine().toUpperCase();
s = s.trim();
char last = s.charAt(s.length() - 1);
if("!?.".indexOf(last) == -1){
System.out.println("INVALID INPUT");
return;
}
StringTokenizer st = new StringTokenizer(s, "!?. ,");
int size = st.countTokens();
String a[] = new String[size];
for(int i = 0; i < a.length; i++)
a[i] = st.nextToken();
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a.length - 1 - i; j++){
if(a[j].length() > a[j + 1].length()){
String temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
else if(a[j].length() == a[j + 1].length()){
if(a[j].compareTo(a[j + 1]) > 0){
String temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
System.out.println(s);
for(int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
}
Comments
Post a Comment