Pig Latin Program in Java

Pig Latin is a method for translating words of the English language into a different language. It is an encrypted word that is generated by using the following steps. The Pig Latin program in Java generates a Pig Latin word based on the input given by a user.

STEP 1: Take a word as input from the user.

STEP 2: Take the first vowel of word and place it at the beginning of the new word. If the vowels are absent in the input string, the Pig Latin encoding is impossible.

STEP 3: Take all the letters following the first vowel of the input word and place them behind the first letter of the new word.

STEP 4: Append all the letters coming before the first vowel of the input word to the new word.

STEP 5: Append ay to the new word. Now, the new word is the Pig Latin word.

Let’s understand the above steps through an example.

Suppose we take the word ‘goat’. The first occurrence of a vowel in the word ‘goat’ is the letter ‘o’. Now, we place the letter ‘o’ at the beginning of the new word. After that, append all the remaining letters (coming after vowel i.e. at) after the vowel. Thus, the new word becomes ‘oat’. Now, append all the letters coming before the first vowel i.e. g to the new word. The new word becomes ‘oatg’.

At last, append ‘ay’ to the new word. Thus, the updated new word is ‘oatgay’ that is a Pig Latin word for the word ‘goat’.

Let’s implement the above steps in a Java program.

Filename: PigLatinExample.java

Output 1:

Output 2:

Explanation: The code written above is completely based on the steps written above. We have taken a string form the user and passed it as argument in the method findPigLatin(). The method findPigLatin() iterates over each character of the input string and invokes the Boolean method isVowel(). In each iteration, the method checks whether vowels are present in the input string or not. The iteration continues till the method isVowel() returns true or the condition part of the for-loop evaluates false. If the loop is terminated because of the break statement, this means the string has at least one vowel. Using the index of the first vowel, we do the Pig Latin encoding of the input string. If the loop is terminated because of the condition part of the loop evaluated false, we cannot do the Pig Latin encoding of the input word. It is because the input word contains no vowel.

Pin It on Pinterest

Share This