In: Computer Science
// Java program to covert a single line english phrase to pig
latin phrase
import java.util.Scanner;
public class PigLatin {
// Prompt and read a phrase to translate
public static String readPhrase (Scanner
console)
{
String phrase;
System.out.print("Please enter a
phrase ==> ");
phrase = console.nextLine();
return phrase;
}
// Convert a phrase to Pig Latin and return it
public static String convertPhrase (String
englishPhrase)
{
String pigLatinPhrase = "";
String words[] =
englishPhrase.split(" "); // get the words from the phrase by
splitting the input phrase using space as the delimiter
// loop to convert each word to pig
latin and add it to resultant string
for(int
i=0;i<words.length;i++)
{
if(i <
words.length-1)
pigLatinPhrase += convertWord(words[i])+"
";
}
// convert the last word to pig
latin
if(words.length > 0)
{
pigLatinPhrase
+= convertWord(words[words.length-1]);
}
return pigLatinPhrase;
}
// Convert a word to Pig Latin and return it
public static String convertWord (String
englishWord)
{
// loop over the word
for(int
i=0;i<englishWord.length();i++)
{
// if character
at index i is a vowel
if(isVowel(englishWord.charAt(i)))
{
// if first character is a vowel, append -way to
the word
if(i == 0)
return
englishWord+"-way";
else // else remove and append the substring
from the start to the index before vowel and append -ay to the
word
return(englishWord.substring(i)+"-"+englishWord.substring(0,i)+"ay");
}
}
return englishWord+"-ay"; // if
word doesn't contain any vowel add -ay at the end of the word
}
// Return true if "c" is a vowel, false
otherwise.
// Handle both lowercase and uppercase letters.
public static boolean isVowel (char c)
{
// return true if c is a,e,i,o or u
in any case
return("aeiouAEIOU".contains(c+""));
}
// Print result of translation
public static void printResult (String englishPhrase,
String pigLatinPhrase)
{
System.out.println(englishPhrase+"\nin Pig Latin
is\n"+pigLatinPhrase);
}
public static void main(String[] args) {
Scanner scan = new
Scanner(System.in);
String englishPhrase =
readPhrase(scan);
String pigLatinPhrase =
convertPhrase(englishPhrase);
printResult(englishPhrase,
pigLatinPhrase);
scan.close();
}
}
//end of program
Output: