【发布时间】:2015-04-17 13:01:11
【问题描述】:
请有人帮我解决一个小问题。 我被分配了将一个英文单词转换为 opish 的任务。 Opish 是一种在每个辅音之后添加字符“op”的语言,如有必要,在下一个元音之前添加字符。 我的代码适用于大多数单词,但是,如果两个辅音彼此相邻,它就会失败。例如,单词 chat 应该是chopatop,但代码返回 cophopatop,因为它不检查下一个字符是否是元音。 代码如下:
公共课翻译 {
/**
* Is char a vowel?
*/
public static boolean isConsonant(char c) {
boolean consonant;
if (c == 'a' || c == 'e' || c == 'i' ||
c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' ||
c == 'O' || c == 'U'){
consonant = false; System.out.println("No");}
else{
consonant = true; System.out.println("Yes");}
return consonant; }
/**
* Is char a vowel?
*/
public static boolean isVowel(char c) {
boolean vowel;
if (c == 'a' || c == 'e' || c == 'i' ||
c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' ||
c == 'O' || c == 'U'){
vowel = true; }
else{
vowel = false; }
return vowel; }
/**
* converts given word to Pig Latin
*/
public static String toPigLatin(String word) {
int i;
boolean c;
for (i = 0; i<word.length(); i++){
c = isConsonant(word.charAt(i));
if (c == false){
String d = word.substring(i,word.length());
System.out.println(d);
String a = word.substring(0,i);
System.out.println(a);
return (d + a + "ay");
}
}
return word;
}
/**
* converts given word to Opish
*/
public static String toOpish(String word) {
int i;
boolean c;
boolean v;
for (i = 0; i<word.length(); i++){
c = isConsonant(word.charAt(i));
v = isVowel(word.charAt(i));
if (c == true) {
String front = word.substring(0,i+1);
String back = word.substring(i+1,word.length());
word = front + "op" + back ;
i=i+3;
System.out.println("word " + word);
}
}
return word;}
} // end class
【问题讨论】:
-
编写单元测试。从简单的案例开始并扩展您的需求集。如果测试失败,请调试它。
-
请参阅stackoverflow.com/a/19161184/1980909 以获得更清晰的 isVowel。此外,无需为 isConsonant 复制所有内容,因为 isConsonant == !isVowel。
-
正如你所说,你不是在检查下一个字母是否是元音......
标签: java