Java将英语转换为Opish

时间:2015-02-16 22:09:05

标签: java

请有人帮我解决一个小问题。 我被赋予了将英语单词转换成opish的任务。 Opish是一种语言,在每个辅音之后添加字符“op”,如果有必要,在下一个元音之前添加。 我的代码适用于大多数单词,但是,如果两个辅音彼此相邻,则会失败。例如,聊天这个词应该是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

1 个答案:

答案 0 :(得分:0)

你没错,你不会检查下一个字符是否是元音。你检查当前的字母并且不做任何事情:

v = isVowel(word.charAt(i));

相反,尝试这样的事情:

//We don't want out of bounds issues
if(i<word.length()){
    v = isVowel(word.charAt(i+1));
} else {
    v = true; //Pretend last character is vowel to force the end 'op'
}

if (c == true && v == 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);
}