Tuesday, October 6, 2009

Java - pig latin generator

 
package javasomethingsomething;
 
public class Main {
    public static void main(String[] args) {
        // all the heavy lifting is done in the PigLatin class 
        PigLatin pg = new PigLatin();
        String pigSentence = "";
        String sentence = "This is going to be a pig latin sentence";
        // iterate over the sentence with for-each and split by " " 
        for (String s:sentence.split(" ")) {
            pigSentence += pg.getPigLatinForWord(s) + " ";
        }
        // added the trim to remove the trailing space 
        System.out.println(pigSentence.trim());
    }
 
}
 
class PigLatin{
 
    public String getPigLatinForWord(String word) {
        int firstVowel = word.length();
        // yes, I included y as a vowel!! 
        String[] vowels = {"a", "e", "i", "o", "u", "y"};
        for(String s:vowels){
            // if indexOf() finds no match it returns -1 
            if ((word.indexOf(s) < firstVowel) && (word.indexOf(s) != -1)) {
                firstVowel = word.indexOf(s);
            }
        }
        return  word.substring(firstVowel, word.length()) +
                word.substring(0, firstVowel) +
                "ay";
    }
}
 

No comments:

Post a Comment