編寫一個將文本翻譯爲假拉丁文並返回的程序。將英語翻譯爲假拉丁文,方法是將每個單詞的第一個字母移動到單詞的結尾,併爲每個單詞添加「ay」。 作爲一個例子,如果你的程序從鍵盤上讀取字符串「快速棕色狐狸」,那麼它應該在屏幕上打印下面的文本:「Hetay uickqay rownbay oxfay」。 你也應該實現與此相反,閱讀「Iay ikelay rogrammingpay」應該在屏幕上打印「我喜歡編程」。編寫一個將文本翻譯爲假拉丁文並返回的程序
public class fakelatin {
public static void main(String[] args)
{
Scanner pig = new Scanner(System.in);
String word; original word
String latin = "";
char first;
boolean cap = false;
String line;
System.out.print("enter line to translate: "); //enter the line to translate
line = pig.nextLine();
pig = new Scanner(line);
// loop through all the words in the line
while (pig.hasNext()) // is there another word?
{
word = pig.next();
first = word.charAt(0);
if ('A' <= first && first <= 'Z') // first is capital letter
{
first = Character.toLowerCase(first);
cap = true;
}
else
cap = false;
// test if first letter is a vowel
if (first=='a' || first=='e' || first=='i' || first=='o' || first=='u')
latin = word + "ay";
else
{
if (cap)
{
latin = "" + Character.toUpperCase(word.charAt(1)); // char to String conversion
latin = latin + word.substring(2) + first + "ay";
}
else
latin = word.substring(1) + first + "ay";
}
System.out.print(latin + " ");
}
}
}
我已經得到了輸出IAY ikelay rogrammingpay我所想要的
import java.util.Scanner;
public class fakelatin2 {
public static void main(String[] args)
{
Scanner pig = new Scanner(System.in);
String word; // original word
String latin = ""; // pig latin translation, init to empty string
char first,last;
boolean cap = false;
String line;
System.out.print("enter line to translate: ");
line = pig.nextLine();
pig = new Scanner(line);
// loop through all the words in the line
while (pig.hasNext()) // is there another word?
{
word = pig.next();
first = word.charAt(0);
last=word.charAt(word.length()-1);
if ('A' <= first && first <= 'Z') // first is capital letter
{
first = Character.toLowerCase(first);
cap = true;
}
else
cap = false;
latin = word.replaceAll("ay", "");
if(cap)
{
latin = "" + Character.toUpperCase(word.charAt(1));
latin=latin+word.substring(word.length()-1);
}
System.out.print(latin + " ");
}
}
}
爲「我ikel rogrammingp」,但沒能得到我得到的輸出「我喜歡編程」回到
'word.replaceAll(「ay」,「」)'似乎很危險,如果你的單詞是play(laypay)?它會變形,你可能想使用'word.replaceAll(「ay $」,「」)'(使用[regex](https://docs.oracle.com/javase/8/docs/api/java) /util/regex/Pattern.html#sum))或'word.substring(0,word.length() - 2)' – phflack
它給出的輸出如「I Iikel Iikelrogrammingp」 – arfa
您刪除「ay」的所有實例,但永遠不要將最後一個字符移動到前面,你可能想'latin = latin.substring(latin.length() - 1)+ latin.substring(0,latin.length() - 1);' – phflack