【问题标题】:Java Converting English to OpishJava 将英语转换为 Opish
【发布时间】: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


【解决方案1】:

你是对的,你没有检查下一个字符是否是元音。你检查了当前的字母并且什么都不做:

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);
}

【讨论】:

  • 感谢您的明确回复!这正是我需要的答案。
猜你喜欢
  • 2021-12-25
  • 1970-01-01
  • 2015-02-15
  • 1970-01-01
  • 2015-07-27
  • 2011-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多