有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

爪哇猪拉丁语翻译移动辅音群

所以我有了基本知识,我只需要找到并移动一组辅音。有什么专业建议吗

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) 个答案

  1. # 1 楼答案

    可以编写一个函数charIsVowel(Char c),检查Char[]数组是否包含c。然后检查每个字母是否都是元音,直到找到一个元音为止。然后将输入的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);
    

    那么你只需要在结尾加上“是”。所以:

    translation += "ay";
    

    这样做的好处是,无论String是以元音还是辅音开头,它都是有效的

    PS:你从不使用userWord1