Arrange Words ISC Computer Science 2012 Practical

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:

(a) Obtain the length of the sentence (measured in words)

(b) 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.util.Scanner;
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();
        char last = s.charAt(s.length() - 1);
        if(".?!".indexOf(last) == -1){
            System.out.println("INVALID SENTENCE");
            return;
        }
        int length = 0;
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(!Character.isLetterOrDigit(ch))
                length++;
        }
        System.out.println("LENGTH: " + length);
        System.out.println("REARRANGED SENTENCE:");
        String a[] = new String[length];
        String w = new String();
        int index = 0;
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(Character.isLetterOrDigit(ch))
                w += ch;
            else{
                a[index++] = w;
                w = "";
            }
        }
        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;
                }
            }
        }
        String t = "";
        for(int i = 0; i < a.length; i++)
            t += a[i] + " ";
        System.out.println(t);
    }
}

Comments

Popular posts from this blog

Encrypt Program ISC Specimen 2023 Theory

No Repeat Program ISC Computer Science 2022 Semester 2 Theory

Bank Inheritance Program ISC Specimen 2023 Theory