我一直在为大学的一个小组项目创建一个 Pig Latin 翻译器(我们不必实际制作翻译器,只需以我们喜欢的任何方式操作字符串,我选择了这个)。
我的翻译器输入的是拉丁文祈祷文,前两行是:
credo in unum deum
patrem omnipotentem
我用以下代码创建了我的翻译器:
public static void pigLatinify(String fname) throws IOException
{
File file = new File("projectdata.txt");
try
{
Scanner scan1 = new Scanner(file);
while (scan1.hasNextLine())
{
Scanner scan2 = new Scanner(scan1.nextLine());
boolean test2;
while (test2 = scan2.hasNext())
{
String s = scan2.next();
char firstLetter = s.charAt(0);
if (firstLetter=='a' || firstLetter=='i' || firstLetter=='o' || firstLetter=='e' ||
firstLetter=='u' || firstLetter=='A' || firstLetter=='I' || firstLetter=='O' ||
firstLetter=='E' || firstLetter=='U')
{
String output = s + "hay" + " ";
System.out.print(output);
}
else
{
String restOfWord = s.substring(1);
String output = restOfWord + firstLetter + "ay" + " ";
System.out.print(output);
}
}
System.out.println("");
}
scan1.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
它很好地输出了整个祈祷,前两行的输出如下:
redocay inhay unumhay eumday
atrempay omnipotentemhay
然而,在真正的猪拉丁语中,单音节词保持不变并在末尾添加“-hay”,因此“it”变为“ithay”,“egg”变为“egghay”,但多音节词添加了“-way”到最后,所以“archery”变成了“archeryway”,“ending”变成了“endingway”。
Java(以及我正在使用的扫描仪类)有没有办法检测一个单词是否是单音节的?
在这一点上我还要指出我只是一个初学者程序员,所以如果有但它非常复杂,请随意说!