Prashnikaप्रश्निका
Code
About
‹ All Computer Science notes

ISC Practicals and Theory - Word Extraction and Count (OOP)

Updated 21 Oct 2026

This version extracts and counts the words of a sentence, without StringTokenizer or split(), using a class Words with a parameterised constructor. Two small methods do the searching: skipSpaces() finds where a word starts and wordEnd() finds where it ends. extract() uses them to print every word with its length, and main reads the sentence, creates the object and calls the methods.

Definition

A word here is a run of characters between spaces. The sentence must end with ., ? or !, otherwise the program prints INVALID INPUT. The terminating character is not part of the last word (Hello. has the word Hello), and extra or leading spaces are skipped, so no empty word is ever counted. Spaces at the two ends of the line are ignored (the constructor trims the sentence). For . alone there is no word, so it is INVALID INPUT.

Algorithm

  1. main reads a whole line with nextLine() into str and creates new Words(str). The constructor stores the sentence in s after trim(), its length in len and sets count = 0.
  2. isValid() returns false if the sentence has fewer than 2 characters or its last character is not ., ? or !.
  3. extract() starts with i = 0 and repeats:
    • i = skipSpaces(i) moves i over spaces to the first letter of the next word. It never goes past the index len - 1 of the terminating character.
    • If i >= len - 1, only the terminating character is left, so the loop stops.
    • e = wordEnd(i) moves along the word to the next space or the terminating character.
    • w = s.substring(i, e) is the word. Increase count, print w and its length, and set i = e.
  4. display() prints Number of words = followed by count.

Program

The constructor stores the sentence, isValid() checks it, skipSpaces() and wordEnd() locate a word, extract() prints the words and counts them, and display() prints the count.

import java.util.Scanner;

/* Class Words extracts the words of a sentence without using StringTokenizer
   or split(), prints each word with its length and prints the word count. */
public class Words
{
    String s;      // the sentence entered by the user
    int len;       // length of the sentence
    int count;     // number of words found

    /* Parameterised constructor. Parameter ss: the sentence entered.
       It stores the sentence without the spaces at its two ends, its length
       and sets count to 0. */
    Words(String ss)
    {
        s = ss.trim();                       // trim() removes the spaces at the two ends
        len = s.length();
        count = 0;
    }

    /* Returns true if the sentence has at least one character before its last
       character and that last character is '.', '?' or '!', otherwise false */
    boolean isValid()
    {
        if (len < 2)                         // empty, or only a terminator
            return false;
        char last = s.charAt(len - 1);       // terminating character
        return last == '.' || last == '?' || last == '!';
    }

    /* Parameter i: an index in the sentence. Returns the index of the first
       character at or after i that is not a space; the index of the
       terminating character (len - 1) is returned if there is none. */
    int skipSpaces(int i)
    {
        while (i < len - 1 && s.charAt(i) == ' ')
            i++;
        return i;
    }

    /* Parameter i: the index of the first letter of a word. Returns the index
       just after the word, which is a space or the terminating character. */
    int wordEnd(int i)
    {
        while (i < len - 1 && s.charAt(i) != ' ')
            i++;
        return i;
    }

    /* Prints every word on its own line with its length and counts the words.
       Extra spaces are skipped and the terminating character is not part of
       the last word. */
    void extract()
    {
        int i = 0;                            // index being examined
        count = 0;
        while (true)
        {
            i = skipSpaces(i);                // move to the start of the next word
            if (i >= len - 1)                 // only the terminating character is left
                break;
            int e = wordEnd(i);               // index just after this word
            String w = s.substring(i, e);     // the word found
            count++;
            System.out.println(w + " (" + w.length() + ")");
            i = e;
        }
    }

    /* Prints the number of words */
    void display()
    {
        System.out.println("Number of words = " + count);
    }

    /* main reads the sentence, creates the object and calls the methods */
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String str = sc.nextLine();           // sentence entered by the user
        Words ob = new Words(str);            // object of class Words
        if (ob.isValid())
        {
            ob.extract();
            ob.display();
        }
        else
            System.out.println("INVALID INPUT");
    }
}

Variable description table

VariableData TypePurpose
sStringData member: the sentence entered by the user
lenintData member: length of the sentence
countintData member: number of words found
ssStringParameter of the constructor: the sentence entered
lastcharThe last character of the sentence, tested in isValid()
iintParameter of skipSpaces() and wordEnd(), and the index being examined in extract()
eintIndex just after the word being extracted
wStringThe word just found
scScannerReads the sentence from the keyboard in main
strStringSentence entered by the user in main
argsString[]Command line arguments of main (not used)
obWordsObject created in main to call the methods

Sample input and output

Sample 1

Enter a sentence:   The   sun rises  in the east!
The (3)
sun (3)
rises (5)
in (2)
the (3)
east (4)
Number of words = 6

Sample 2

Enter a sentence: Hello.
Hello (5)
Number of words = 1

Sample 3

Enter a sentence: Is it raining ?
Is (2)
it (2)
raining (7)
Number of words = 3

Sample 4

Enter a sentence: Good morning
INVALID INPUT

Sample 5

Enter a sentence: .
INVALID INPUT

Sample 6

Enter a sentence: Good evening.   
Good (4)
evening (7)
Number of words = 2

One value per line

Dry run

Take the third sample, Is it raining ?, which has len = 15; the terminating character ? is at index 14.

Stepi beforeskipSpaces(i)wordEndwcount afteri after
1002Is12
2235it25
35613raining313
41314 (index 13 is a space, then the limit len - 1 is reached)not callednone3stops, since 14 >= 14

The program prints Is (2), it (2), raining (7) and Number of words = 3, the same as the real run above.

Variations

  1. Longest word "Accept a sentence and display the longest word and its length."
  2. Reverse each word "Accept a sentence and display it with every word reversed, keeping the order of the words."
  3. Words starting with a vowel "Accept a sentence and count the words that begin with a vowel."