我正在尝试创建一个将英语翻译为PigLatin的程序。我有大部分组件,但如果我输入多个单词,它只翻译第一个单词。问题在哪里以及如何解决。
public class PigLatin{
public static String translate(String phrase){
String [] returnArray=phrase.split(" ");
String [] translateArray=new String [returnArray.length];
for(int i=0;i<returnArray.length;i++){
translateArray[i]=translateWord(returnArray[i]);
}
return StringLib.join(translateArray, " ");//translated Array
}
public static String translateWord(String word) {
String tword=word;
int indexVowel=indexOfFirstVowel(tword);
if(indexOfFirstVowel(tword)==0){
tword=tword+"yay";
}
else {
tword=tword.substring(indexOfFirstVowel(tword),tword.length())+tword.substring(0,indexOfFirstVowel(tword))+"ay";
}
return tword;
}
public static int indexOfFirstVowel(String word) {//check where the first vowel is
String vowels = "aeiouy";
String loweredWord=word.toLowerCase();
for (int index=0;index<loweredWord.length();index++){
if(vowels.contains(String.valueOf(loweredWord.charAt(index)))){
return index;
}
}
return -1;
}
public static void main(String [] args){
Scanner inp=new Scanner(System.in);
System.out.println("Please enter a phrase:");
String trans=translate(inp.next());
System.out.println("Here is your phrase in Pig Latin.");
System.out.println(trans);
}
String.join将数组转换为String,这是代码
public class StringLib {
public static String join(String[] strs, String sep) {
String joined = "";
if (strs.length > 0) {
joined = strs[0];
for (int i = 1; i < strs.length; i++) {
joined = joined + sep + strs[i];
}
}
return joined;
}
答案 0 :(得分:2)
在main
方法
String trans = translate(inp.next());
向
String trans = translate(inp.nextLine());