猪拉丁语翻译 - 移动辅音簇

时间:2018-02-04 06:55:14

标签: java loops if-statement

所以我有基础知识,我只需要找到并移动辅音簇。任何专业提示?

import java.util.Scanner;
public class PigLatinTranslator
{

   public static void main (String[] args){

         Scanner in = new Scanner (System.in);
         String userWord = ""; // original Word
         String userWord1 = "";// transition word
         String Translation = ""; // Translated word
         char x = ' '; //this is a temp. character.

         //Get word from User.
         System.out.println("Hi, Welcome to your personal Pig-Latin Translator!");
         System.out.println("Enter in any word! : ");
         userWord = in.nextLine();
         boolean doAgain = true;
         //begining of Loop 
         do
         {
            //Get the first Character
            x = userWord.charAt(0);

            if("AEIOUYaeiouy".indexOf(x) != -1){
            //Check weather or not the first charcater is a vowell
            System.out.println(userWord + "way");            
            }
            else
            {
            userWord = userWord.substring(1);
            System.out.print(userWord);
            do{
               userWord = userWord.substring(1);
               if ("AEIOUYaeiouy".indexOf(x) != -1){
               System.out.print(x);
               }
               else{
               System.out.print("");
               }
               }while (doAgain);
               System.out.println("ay");
               }
            //Prompt user to quit or continue

            System.out.println("Press Q to quit, or enter another word to be translated: ");
            userWord = in.nextLine();

            } while (!userWord.equalsIgnoreCase("Q"));
   }
}

1 个答案:

答案 0 :(得分:0)

您可以编写一个函数charIsVowel(Char c)来检查Char[]数组是否包含c。然后通过你的String检查每个字母是否是元音,直到找到一个字母为止。然后将输入的substring从开头移动到第一个元音的索引到结尾。像这样:

public static boolean charIsVowel(char c) {
    char[] vowels = { 'a', 'e', 'i', 'o', 'u' };

    for(char ch : vowels) {
        if(c == ch) {
            return true;
        }
    }

    return false;
}

int index = 0;
for(; index<userWord.length(); index++) {
    if(charIsVowel(userWord.charAt(index))) {
        break;
    }
}

String translation = userWord.substring(index) + "-" + userWord.substring(0, index);

然后您需要做的就是在结尾添加“ay”。所以:

translation += "ay";

这样做的好处是,无论String是以元音还是辅音开头,它都能正常工作。

PS:你永远不会使用userWord1