×

Pig Latin Program in Java

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

// importing the Scanner class
import java.util.Scanner;
public class PigLatinExample
{
// Method of checking vowels  
public static Boolean isVowel(char c)
{
    // handling the case in-sensitivity
    if(c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' ||
       c == 'I' || c == 'o' || c == 'O' || c == 'u' || c == 'U')
       // if we reach here, we got a vowel
       return true;
       //if we reach here, we got a consonant
       return false;
}
// Method for encoding the input string
public static String findPigLatin(String input)
{
    // calculating length of the string
    int size = input.length();
    String pigL = ""; // contains final answer
    int i;
    // loop for finding the first vowel in the string
    for(i = 0; i < size; i++)
    {
        if(isVowel(input.charAt(i)))
        {
            // got the first vowel,
            // getting out of the for-loop
            break;
        }
    }
    // vowels are not present in the input string.
    if( i == size)
    {
        // retuning an empty string
        return "";
    }
    // if we reach here, at least one vowel is present in the input string
    // the first vowel and following letters should come
    // as it is in the encoded string
    pigL = input.substring(i);
    // Appending the letters appearing before
    // the first vowel in the input string
    pigL = pigL + input.substring(0, i - 0);
    // Final step, appeding the string "ay"
    pigL = pigL + "ay";
    // returning the encoded Pig Latin string
    return pigL;
}
public static void main(String argvs[])
{
        String str = ""; // contains the encrypted Pig Latin string
        // Creating an object of the Scanner class
        Scanner scnr = new Scanner(System.in); 
        System.out.println("Enter a string ");
        // reading input given from the user
        str = scnr.nextLine();
        // calling the method findPigLatin() and storing the outcome
        String ans = findPigLatin(str);
        // displaying the result
        if(ans.equals(""))
        {
            System.out.println("The Pig Latin encoded string of the input string " + str + " is not possible");   
        }
        else
        {
            System.out.println("The Pig Latin encoded string of the input string " + str + " is " + ans);
        }
}
} 

Output 1:

 Enter a string
trIpptt
The Pig Latin encoded string of the input string trIpptt is Ipptttray 

Output 2:

 Enter a string
ptyrsdf
The Pig Latin encoded string of the input string ptyrsdf is not possible 

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.


Related Topics

Java Future Example

Future is an interface in the Java language that is a part of  java.util.concurrent package. It serves as a symbol for the output of an asynchronous computation. The interface offers ways to determine whether a computation has finished,  wait for it to finish, and receive its result. Once the task or calculation is finished, it cannot be undone. A Future interface offers ways to determine whether the computation is finished, to wait for it to finish, and to receive the computation's results. When the computation...

3 minutes read.

Java Try Resource

In Java, a try argument that specifies one or more resources is known as a try-with-resources statement. When your program is finished utilizing an object, it must be closed, which...

4 minutes read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

Thread States in Java

An Item's Life Cycle (Thread States) A thread can be in any of the states mentioned above at any given time in Java. They are as follows: New Active I'm blocked or waiting Temporary...

3 minutes read.

Automatic Resource Management

In computer programming, resource management refers to the wide set of techniques for the effective management of the system resources. There are two ways of management of resources: The computer program itself...

2 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

4 minutes read.

How to make Java Projects

Ant and Maven are both offered by NetBeans for the development of Java applications. When using Ant, the IDE creates an Ant build script depending on the settings you select...

6 minutes read.

Java copy file

There are for the most part 3 methods for duplicating documents utilizing java language. They are as given underneath: Utilizing File StreamUtilizing FileChannel ClassUtilizing Files class. 1. Using File Stream: Here we are...

5 minutes read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array. Input:  arr[] = {10, 11, 13, 15, 34, 51} Output: The...

6 minutes read.

Java String Reader

StreamReaderClass: This class is present in the java.io package. It is a character stream in which string act as a source.This method provides to read characters from a string. Character Stream: This class...

3 minutes read.

Get yesterdays date by no of days in Java

In this tutorial, we are going to learn how to get yesterday’s date by the no of days in Java. Using the Calendar class, one can get the current date....

1 minute read.

Salesman Problem in Java

The Traveling Salesman Problem determines the shortest path that visits each city approximately once and loops back to the starting location. Another Java problem that is most like the Traveling...

5 minutes read.

Java Coding Software

Desktop and web apps are created using Java, an object-oriented programming language. Java code may be executed on any platform, making it platform-independent. A text editor, tool, or piece of...

9 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

Highest precedence in Java

In Java, the operator is the first thing that springs to mind when discussing precedence. The order in which the operators in an expression are evaluated is controlled by a...

3 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.

Getting the Day from the Date in Java?

To extract the day's name from the date, we will write Java application. When dealing the date and time in Java, the following classes are used. Class for Calendars: This class is...

6 minutes read.