Categories
Class 11 Class 12

Arrange Words based on Length of Words ISC 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.io.*;
import java.util.StringTokenizer;
class Arrange{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Sentence: ");
        String s = br.readLine();
        s = s.trim();
        s = s.toUpperCase();
        int len = s.length();
        char last = s.charAt(len - 1);
        switch(last){
            case '.':
            case '?':
            case '!':
            break;
            default:
            System.out.println("INVALID INPUT");
            return;
        }
        System.out.println(s);
        StringTokenizer st = new StringTokenizer(s, "? .!,");
        int count = st.countTokens();
        String a[] = new String[count];
        for(int i = 0; i < count; 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].compareTo(a[j + 1]) > 0){
                    String temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }
        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;
                }
            }
        }
        for(int i = 0; i < a.length; i++)
            System.out.print(a[i] + " ");
        System.out.println();
    }
}

By admin

I am a Computer Science teacher in one of the renowned schools in India. I teach Java programming language to my students, and I maintain a website happycompiler.com

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.