我不明白为什么这种方法不起作用。它编译,但会引发运行时错误。
这是代码。这是一个Pig Latin-izer。它应该将短语分成单词,然后格式化这些单词,然后将它们全部放回到一个ArrayList中(稍后我可能会更改它。)我不明白为什么这不能正常运行。
import java.util.*;
public class OinkerSpine
{
public ArrayList<String> pigLatin (String phrase)
{
phrase = phrase.replaceAll(".", " .");
phrase = phrase.replaceAll(",", " ,");
phrase = phrase.replaceAll("!", " !");
//phrase = phrase.replaceAll("?", " ?");
phrase = phrase.replaceAll("'", " '");
String []words = phrase.split(" ");
ArrayList <String> Endphrase = new ArrayList <String> ();
final String AY = "ay";
final String YAY = "-yay";
String endword = "";
for(int i=0; i < words.length; i++)
{
String firstletter;
String restofword;
String secondletter;
if (words[i].length() == 1)
{
firstletter = words[i];
restofword = "";
}
else
{
firstletter = words[i].substring(0, 1);
restofword = words[i].substring(1);
}
boolean firstIsUpper = (firstletter.equals(firstletter.toUpperCase()));
if (firstIsUpper)
{
firstletter = firstletter.toLowerCase();
secondletter = restofword.substring(0, 1);
restofword = restofword.substring(1);
secondletter = secondletter.toUpperCase();
restofword = secondletter + restofword;
}
if (firstletter.equals("a") || firstletter.equals("e") ||
firstletter.equals("i") || firstletter.equals("o") ||
firstletter.equals("u"))
{
endword = firstletter + restofword + YAY;
}
else
{
endword = restofword + "-" + firstletter + AY;
}
endword = endword.replaceAll(" .", ".");
endword = endword.replaceAll(" ,", ",");
endword = endword.replaceAll(" !", "!");
//endword = endword.replaceAll(" ?", "?");
endword = endword.replaceAll(" '", "'");
Endphrase.add(endword);
}
return Endphrase;
}
}
这里有什么?
答案 0 :(得分:1)
如果restofword
或word[i]
为空字符串
secondletter = restofword.substring(0, 1);
或
firstletter = words[i].substring(0, 1);
答案 1 :(得分:0)
你可能在这里替换了太多字符:
phrase = phrase.replaceAll(".", " .");
为substring
留下不足的字母。你可能想要
phrase = phrase.replaceAll("\\.", " .");
或更好
phrase = phrase.replace(".", " .");