CS99 |
Fundamental Programming Concepts
Summer 2001 |
|
Lab 9: Bonus (Pig Latin Translator)
PigLatinTranslator.java |
import java.util.StringTokenizer; /* You must include the previous line if you use the StringTokenizer class! */ /** * class PigLatinTranslator represents a translation system from English to Pig Latin. */ class PigLatinTranslator { /** * Translates a sentence of words into Pig Latin */ public static String translate( String sentence ) { sentence = sentence.toLowerCase(); StringTokenizer tokenizer = new StringTokenizer( sentence ); String ans = ""; while ( tokenizer.hasMoreTokens() ) { ans += translateWord( tokenizer.nextToken() ) + " "; } return ans; } /** * Translates one word into Pig Latin. If the word begins with a vowel, the suffix "yay" * is appended to the word. Otherwise the first letter or two are moved to the end of the * word and "ay" is appended. */ private static String translateWord( String word ) { String trans = ""; if ( beginsWithVowel ( word ) ) trans = word + "y"; else if ( beginsWithPrefix( word ) ) trans = word.substring(2) + word.substring(0, 2); else trans = word.substring(1) + word.charAt( 0 ); return trans + "ay"; } /** * Determines if the specified word begins with a vowel. */ private static boolean beginsWithVowel( String word ) { return word.charAt( 0 ) == 'a' || word.charAt( 0 ) == 'e' || word.charAt( 0 ) == 'i' || word.charAt( 0 ) == 'o' || word.charAt( 0 ) == 'u'; } /** * Determines if the specified word begins with a particular two-character prefix. */ private static boolean beginsWithPrefix( String str ) { str = str.toLowerCase(); return str.startsWith("bl") || str.startsWith("pl") || str.startsWith("br") || str.startsWith("p") || str.startsWith("ch") || str.startsWith("sh") || str.startsWith("cl") || str.startsWith("sl")|| str.startsWith("cr") || str.startsWith("sp") ||str.startsWith("dr") || str.startsWith("sr") || str.startsWith("fl") || str.startsWith("st") ||str.startsWith("fr") || str.startsWith("th")|| str.startsWith("gl") || str.startsWith("tr") || str.startsWith("gr") || str.startsWith("wh")|| str.startsWith("kl") || str.startsWith("wr") ||str.startsWith("ph"); } } |
PigLatin.java
class PigLatin { public static void main( String[] args ) { TokenReader in = new TokenReader( System.in ); String cont = "y"; String sentence = ""; do { System.out.println("Enter a sentence (no punctuation): "); sentence = in.readLine(); System.out.println("\nThat sentence in Pig Latin is:"); System.out.println(PigLatinTranslator.translate( sentence ) +"\n"); System.out.print("Translate another sentence (y/n)? " ); cont = in.readString(); System.out.println("\n"); } while( cont.equalsIgnoreCase("y") ); } } |