java语言的科学与艺术-PigLatin.java
1 /* 2 * File: PigLatin.java 3 * -------------- 4 * This file takes a line of text and converts each word into Pig Latin. 5 * The rules for forming Pig Latin words are as follows: 6 * - If the word begins with a vowel, add "way" to the end of the word. 7 * - If the word begins with a consonant, extract the set of consonants up 8 * to the first vowel, move that set of consonants to the end of the word, 9 * and add "ay". 10 */ 11 12 import acm.program.*; 13 import java.util.*; // for the StringTokenizer class 14 public class PigLatin extends ConsoleProgram { 15 public void run(){ 16 println("This program translates a line into Pig Latin,"); 17 String line = readLine("Enter a line: "); 18 println(translateLine(line)); 19 } 20 /* Translates a line to Pig Latin, word by word */ 21 private String translateLine(String line){ 22 String result = ""; 23 StringTokenizer tokenizer = 24 new StringTokenizer(line, DELIMITERS, true); 25 while(tokenizer.hasMoreTokens()) { 26 String token = tokenizer.nextToken(); 27 if (isWord(token)){ 28 token = translateWord(token); 29 } 30 result += token; 31 } 32 return result; 33 } 34 /* Translates a word to Pig Latin and returns the translated word */ 35 private String translateWord(String word) { 36 int vp = findFirstVowel(word); 37 if(vp == -1){ 38 return word; 39 } else if (vp == 0){ 40 return word + "way"; 41 } else { 42 String head = word.substring(0, vp); 43 String tail = word.substring(vp); 44 return tail + head + "ay"; 45 } 46 } 47 48 /* Returns the index of the first vowel in the word (-1 if none) */ 49 private int findFirstVowel(String word) { 50 for(int i = 0; i < word.length(); i++) { 51 if(isEnglishVowel(word.charAt(i))) return i; 52 } 53 return -1; 54 } 55 56 /* Returns true if the character is a vowel */ 57 private boolean isEnglishVowel(char ch) { 58 switch (Character.toLowerCase(ch)) { 59 case 'a': case 'e': case 'i': case 'o': case 'u': 60 return true; 61 default: 62 return false; 63 } 64 } 65 66 /* Returns true is token is a "word" (all character are letters) */ 67 private boolean isWord(String token) { 68 for (int i = 0; i < token.length(); i++) { 69 char ch = token.charAt(i); 70 if(!Character.isLetter(ch)) return false; 71 } 72 return true; 73 } 74 75 /* Defines the characters that delimit a token */ 76 private static final String 77 DELIMITERS = "!@#$%^&*()_-+={[}]:;\"'<,>.?/~`|\\ "; 78 }
posted on 2012-12-31 18:03 mybluecode 阅读(467) 评论(0) 编辑 收藏 举报