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

ISC Practicals and Theory - Piglatin

Updated 21 Oct 2026

Pig Latin is a word game in which every English word is rewritten by a fixed rule. This program, written in the main method alone, reads a sentence that ends with a full stop, question mark or exclamation mark, converts every word to Pig Latin and prints the new sentence with the same terminator. The words are cut out of the sentence with charAt() and substring() only, with no split() or StringTokenizer.

Definition

The rule used here, with the vowels A, E, I, O, U:

  • If a word begins with a vowel, add AY at the end.
  • Otherwise move the leading consonants, up to the first vowel, to the end of the word and then add AY.

Examples:

  • OPEN begins with a vowel, so it becomes OPENAY.
  • THE: the consonants TH move to the end, giving E + TH + AY = ETHAY.
  • QUICK: the first vowel is U, so only Q moves, giving UICKQAY. (QU is not treated as a pair.)
  • RHYTHM has no vowel at all. The whole word would move to the end, so it comes out as RHYTHMAY.

Decisions made in this program:

  • The sentence is converted to upper case with toUpperCase() and the output is in upper case.
  • Y is not a vowel, so WHY becomes WHYAY and TRY becomes TRYAY.
  • A word with no vowel gets AY added to the unchanged word.
  • The array holds at most 50 words; extra words are ignored.
  • Characters other than letters (commas, digits) stay inside the word and are treated as consonants.

Algorithm

  1. Read the sentence, remove the spaces at its two ends with trim() and convert it to capitals with toUpperCase(). It is valid only if it has at least 2 characters and ends in ., ? or !; otherwise print INVALID INPUT and stop.
  2. Cut out the words: for i from 0 to len - 2 (before the terminator), a character that is not a space is added to the word w; a space after a word stores w in the array words (at most 50 words) and makes w empty. After the loop the last word is stored too.
  3. Convert each word x of the array. Find p, the index of its first vowel (A, E, I, O or U), by skipping the leading consonants.
    • If p == 0, the word begins with a vowel: add AY at its end.
    • Otherwise move the part before the first vowel to the end and add AY: x.substring(p) + x.substring(0, p) + "AY". If the word has no vowel at all, p equals its length, so the whole word moves and the result is the word followed by AY.
  4. Join the converted words with single spaces and add the terminator at the end. Print the sentence.

Program

The first for loop in main fills the array words, and the second converts each word and joins the result in res.

import java.util.*;
public class PigLatin
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a sentence:");
        String sent = sc.nextLine().trim().toUpperCase();   // the sentence (upper case, trimmed)
        int len = sent.length();
        boolean valid = false;                  // true if the sentence ends with . ? or !
        if (len >= 2)
        {
            char last = sent.charAt(len - 1);   // terminator of the sentence
            valid = last == '.' || last == '?' || last == '!';
        }
        if (!valid)
        {
            System.out.println("INVALID INPUT");
            return;
        }
        String words[] = new String[50];        // the words of the sentence, one per element (at most 50)
        int count = 0;                          // number of words stored in the array
        String w = "";                          // word being built
        for (int i = 0; i < len - 1; i++)       // stop before the terminator
        {
            char ch = sent.charAt(i);
            if (ch != ' ')
                w = w + ch;                     // letter: add to current word
            else if (!w.equals(""))             // space after a word: store it
            {
                if (count < words.length)
                    words[count++] = w;
                w = "";
            }
        }
        if (!w.equals("") && count < words.length)   // last word
            words[count++] = w;
        String res = "";                        // converted sentence
        for (int i = 0; i < count; i++)
        {
            String x = words[i];                // the word being converted
            int p = 0;                          // index of the first vowel
            while (p < x.length() && "AEIOU".indexOf(x.charAt(p)) < 0)
                p++;                            // skip leading consonants
            if (p == 0)
                res = res + x + "AY";           // begins with a vowel
            else
                res = res + x.substring(p) + x.substring(0, p) + "AY";   // p == length: the whole word moves
            if (i < count - 1)
                res = res + " ";
        }
        res = res + sent.charAt(len - 1);       // add '.', '?' or '!'
        System.out.println(res);
    }
}

Variable description table

VariableData TypePurpose
argsString[]Command line arguments of main; not used
scScannerReads the input typed by the user
sentStringThe sentence typed by the user, in capitals and trimmed
lenintLength of sent
validbooleanTrue if the sentence has enough characters and ends with ., ? or !
lastcharThe last character of the sentence, the terminator
wordsString[]The words of the sentence, one per element
countintNumber of words stored in words
wStringThe word being built while cutting out the words
iintLoop counter over the characters, then over the words
chcharThe character being examined
resStringThe converted sentence
xStringThe word being converted
pintIndex of the first vowel of x

Sample input and output

Sample 1

Enter a sentence:
Open the door.
OPENAY ETHAY OORDAY.

Sample 2

Enter a sentence:
The   quick brown fox is here!
ETHAY UICKQAY OWNBRAY OXFAY ISAY EREHAY!

Sample 3

Enter a sentence:
Why try rhythm?
WHYAY TRYAY RHYTHMAY?

Sample 4

Enter a sentence:
Hello world
INVALID INPUT

One value per line

Dry run

Input Open the door. After the input is read, sent = OPEN THE DOOR. (14 characters). The sentence is valid as the last character is .. The word-cutting loop runs for i = 0 to 12 (len = 13).

ichw after the stepcount
0 to 3O, P, E, NOPEN0
4spacestored in words[0], w = empty1
5 to 7T, H, ETHE1
8spacestored in words[1], w = empty2
9 to 12D, O, O, RDOOR2
after loopDOOR stored in words[2]3

Now each word is converted.

WordpResult
OPEN0 (O is a vowel)OPEN + AY = OPENAY
THE2 (T, H skipped, E is a vowel)E + TH + AY = ETHAY
DOOR1 (D skipped, O is a vowel)OOR + D + AY = OORDAY

The words are joined with single spaces and the terminator . is added, so res = OPENAY ETHAY OORDAY., the same as the real run above.

Variations

  1. Reverse each word "Write a program to accept a sentence and reverse every word of it, keeping the order of the words."
  2. Longest word "Write a program to accept a sentence and display the number of words and the longest word."
  3. Capitalise words "Write a program to accept a sentence and change the first letter of every word to upper case."
  4. Pig Latin using recursion "Convert a word to Pig Latin using a recursive method."