In: Computer Science
In Java.This program will translate a word into pig-latin. Pig-latin is a language game in which words in English are altered, usually by removing letters from the beginning of a word and arranging them into a suffix. The rules we will use for the pig-latin in this program are as follows: If a word starts with a consonant, split the word at the first instance of a vowel, moving the beginning consonants to the end of the word, following a '-'. Then add 'ay' at the end of the word. Vowels are: a, e, i, o, u (Notice: We are not considering y a vowel for this program) If a word starts with a vowel add the word "yay" at the end of the word following a '-'. Examples: hello translates to ello-hay flare translates to are-flay it translates to it-yay A more detailed explanation of the requirements for each method will be in the method header comments - please follow these closely. Suggested order of completion: isVowel() then pigLatin().
Sol:
Here is the java code for above problem with proper comments just as mentioned in the question. The program uses two functions- isVowel() and pigLatin() to complete the task.
Code:
//java program for pig latin
class Main {
//isVowel function returns 1 if a character passed is vowel and returns 0 if it's not a vowel
static boolean isVowel(char c) {
return (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' ||
c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}
//defining pigLatin function which will return pigLatin based on the word
//if the word starts with a vowel the -yay will be added at the end
//if the word starts with a consonant then it'll be checked for the first occurrence of vowel
//and returns the word like (flare- are-flay)
//if the word doesn't have a vowel then piglatin is not possible
static String pigLatin(String s) {
// the index of the first vowel is stored.
int len = s.length();
int index = -1;
if (isVowel(s.charAt(0))){
return s+ "-" + "yay";
}
for (int i = 0; i < len; i++)
{
if (isVowel(s.charAt(i))) {
index = i;
break;
}
}
// Pig Latin is possible only if vowels
// is present
if (index == -1)
return "-1";
// Take all characters after index (including
// index). Append all characters which are before
// index. Finally append "ay"
return s.substring(index) + "-" +
s.substring(0, index) + "ay";
}
// Main method
public static void main(String[] args) {
String str = pigLatin("flare");
if (str == "-1")
System.out.print("No vowels found." +
"Pig Latin not possible");
else
System.out.print(str);
}
}
Sample Output: