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

ISC Practicals and Theory - Sentence Terminator Validation (OOP)

Updated 21 Oct 2026

This program checks that a sentence ends with a full stop, a question mark or an exclamation mark. Here the sentence is given to the object through a parameterised constructor: main reads the line, creates the object with it and calls display(). A valid sentence gets its terminator, its kind and its word count printed; anything else prints INVALID INPUT.

Definition

A sentence is valid when its last non-space character is ., ? or ! and at least one word comes before it. The terminator suggests the kind: . assertive (declarative), ? interrogative, ! exclamatory.

A word is a run of non-space characters; it begins at a non-space character that is at index 0 or has a space just before it. The terminator is not counted as a word. Words are counted with charAt() and length() only, with no split() or StringTokenizer.

  • How are you ? is valid, ends with ? and has 3 words.
  • Hello. How are you is invalid: the full stop is in the middle, not at the end.
  • . alone is invalid: there is no word.
  • Trailing spaces after the terminator are ignored; an empty or blank line is invalid.
  • Only spaces separate words, so Stop.Look! counts as 1 word.

Algorithm

  1. main reads the whole line with nextLine() into text and creates ob = new Sentence(text). The constructor stores it in str and sets last = -1, term = space and words = 0.
  2. main calls ob.display(), which calls isValid().
  3. isValid() first calls findLast(): starting from the end of str it moves left past spaces, so last is the index of the last non-space character (-1 if none).
    • If last is -1, return false.
    • Store str.charAt(last) in term; if it is not ., ? or !, return false.
    • Store the result of countWords() in words and return words > 0.
  4. countWords() looks at indices 0 to last - 1, adding 1 to c at every non-space character that is the first character or follows a space.
  5. For a valid sentence display() prints term, kind() (Assertive, Interrogative or Exclamatory) and words; otherwise it prints INVALID INPUT.

Program

The class Sentence takes the sentence in its constructor. findLast(), countWords(), isValid() and kind() each do one job.

import java.util.Scanner;

/* Class Sentence checks whether a sentence ends with a valid terminator
   (. ? !) and, if so, reports the terminator, the kind of sentence and
   the number of words. The sentence is passed to the constructor. */
public class Sentence
{
    String str;    // stores the sentence entered by the user
    int last;      // index of the last character that is not a space (-1 if none)
    char term;     // stores the terminator found at the end of the sentence
    int words;     // stores the number of words in the sentence

    /* Parameterised constructor. Parameter s: the sentence typed by the user.
       Stores it in str and initialises the other data members. */
    Sentence(String s)
    {
        str = s;
        last = -1;
        term = ' ';
        words = 0;
    }

    /* Finds the index of the last non-space character of str and stores it
       in last. Trailing spaces are therefore ignored. */
    void findLast()
    {
        last = str.length() - 1;
        while (last >= 0 && str.charAt(last) == ' ')   // skip trailing spaces
            last--;
    }

    /* Returns the number of words in str before the terminator.
       A word begins at a non-space character that is the first character
       or follows a space. Characters up to index last-1 are examined. */
    int countWords()
    {
        int i, c = 0;
        for (i = 0; i < last; i++)
        {
            if (str.charAt(i) != ' ' && (i == 0 || str.charAt(i - 1) == ' '))
                c++;
        }
        return c;
    }

    /* Returns true if the sentence is valid: the last non-space character
       is '.', '?' or '!' and there is at least one word before it.
       Also stores term and words. */
    boolean isValid()
    {
        findLast();
        if (last < 0)                       // empty line or only spaces
            return false;
        term = str.charAt(last);
        if (term != '.' && term != '?' && term != '!')
            return false;
        words = countWords();
        return words > 0;                   // a lone terminator is not a sentence
    }

    /* Returns the kind of sentence suggested by the terminator */
    String kind()
    {
        if (term == '.')
            return "Assertive";
        if (term == '?')
            return "Interrogative";
        return "Exclamatory";
    }

    /* Prints INVALID INPUT or the terminator, kind and word count */
    void display()
    {
        if (isValid())
        {
            System.out.println("Terminator: " + term);
            System.out.println("Kind of sentence: " + kind());
            System.out.println("Number of words: " + words);
        }
        else
            System.out.println("INVALID INPUT");
    }

    /* main reads the sentence, creates the object and calls display() */
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String text = sc.nextLine();            // whole line, spaces allowed
        Sentence ob = new Sentence(text);       // object of class Sentence
        ob.display();
    }
}

Variable description table

VariableData TypePurpose
strStringData member: the sentence entered by the user
lastintData member: index of the last non-space character of str (-1 if there is none)
termcharData member: the terminator found at the end of the sentence
wordsintData member: number of words in the sentence
sStringParameter of the constructor: the sentence passed in from main
iintLoop counter in countWords(): index of the character being examined
cintLocal variable of countWords(): number of words found so far
scScannerReads the line from the keyboard in main
textStringLocal variable of main: the line typed by the user
obSentenceObject created in main with text
argsString[]Command line arguments of main (not used)

Sample input and output

Sample 1

Enter a sentence: India is my country.
Terminator: .
Kind of sentence: Assertive
Number of words: 4

Sample 2

Enter a sentence:    How   are  you ?   
Terminator: ?
Kind of sentence: Interrogative
Number of words: 3

Sample 3

Enter a sentence: What a lovely day !
Terminator: !
Kind of sentence: Exclamatory
Number of words: 4

Sample 4

Enter a sentence: Hello. How are you
INVALID INPUT

Sample 5

Enter a sentence: .
INVALID INPUT

Sample 6

Enter a sentence: Stop.Look!
Terminator: !
Kind of sentence: Exclamatory
Number of words: 1

One value per line

Dry run

Input What a lovely day ! (19 characters: What at 0 to 3, a at 5, lovely at 7 to 12, day at 14 to 16, space at 17, ! at 18). findLast() finds no trailing space, so last = 18 and term = !, which is valid. countWords() examines indices 0 to 17.

istr.charAt(i)Non-space and (i = 0 or space before)?c
0Wyes, first character1
1 to 3h, a, tno1
4spaceno1
5ayes, space before2
6spaceno2
7lyes, space before3
8 to 12o, v, e, l, yno3
13spaceno3
14dyes, space before4
15, 16a, yno4
17spaceno4

The loop ends before index 18, so words = 4 (the ! is not counted). kind() returns Exclamatory, so the program prints Terminator: !, Kind of sentence: Exclamatory and Number of words: 4, the same as the real run above.

Variations

  1. Count sentences "Write a program to accept a paragraph and count the number of sentences ending with . ? or !"
  2. Longest word "Write a program to accept a sentence and display its longest word."