×

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

Misc Operators in Java

In this article, we are going to learn about the misc operators in Java. Misc operators are nothing but the miscellaneous operators. The java programming language supports some of the...

4 minutes read.

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.

What is string in Java why it's immutable

String in Java Strings are a series of characters commonly used in Java language, which are considered objects in the Java. To create and manipulate strings, java will provide the String...

4 minutes read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Java Implements Keyword

To understand about the keyword implements we need to learn about the concept of the interfaces and inheritance in java programming languages. So let us learn about the interface and...

3 minutes read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

Constructor Chaining and Constructor Overloading in Java

Constructor Chaining Constructor chaining and constructor overloading are two confusing terms. Let's first understand constructor chaining.Constructor chaining is the process of calling one constructor from another constructor using the same object....

2 minutes read.

Java Case Keyword

Case keyword: In this article we are going to learn the concept of a java case keyword.Generally, java case keyword is used with the switch statements.Case keyword is implemented in conditional...

3 minutes read.

Java Short Keyword

Java supports eight different primitive datatypes. The language has predefined primitive datatypes that are given keyword names. Let's take a closer look at each of the eight primitive data types....

3 minutes read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.

Java Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

Difference between print() and println() in Java

In this tutorial, we will discuss the differences between print and println in Java language. There are mainly two methods to display the text on the console printprintln The above two methods are...

4 minutes read.

Java String join() method

Java String join() method returns a joined String with given delimiter Syntax: public static String join(CharSequence delimeter,charSequence...elements) public static String join(CharSequence delimeter,Iterable<?extens charSequence>elements) Parameters: delimiter: char value to be added with each element elements: char value...

1 minute read.

Java Math acos() Method

The acos() method of Math class computes the trigonometric Arc Cosine (inverse of cosine ) of an angle. The value returned is between 0.0 to pi. Syntax: public static double acos(double a) Parameters: The...

1 minute read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

How to Convert String to Integer in Java

How to convert String to int in Java You need to convert String into int if you want to perform a mathematical operation on string which contains digits. To do so,...

3 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.