我试图解决编码蝙蝠的问题并且无法通过一项测试。StringIndexOutOfBoundsException检查单词的最后一个字母时为-1
给定一个字符串,计算以'y'或'z'结尾的单词数 - 所以'heavy'中的'y'和'fez'中的'z'数,而不是'y'在“黄色”(不区分大小写)。如果紧跟在字母后面没有字母,我们会说y或z在单词的末尾。 (注:Character.isLetter(char)的测试,如果一个字符是字母文字。)
这里是我的代码:
public int countYZ(String str) {
int count = 0;
str = str.toLowerCase();
String[] newArr = str.split("[\\s:0-9-!]+");
for (String word : newArr) {
if (word.charAt(word.length() - 1) == 'y' ||
word.charAt(word.length() - 1) == 'z') {
count++;
}
}
return count;
}
但是我无法通过这个测试,它显示了这个错误:
countYZ( “!!日 - YAZ !!”)→2
Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:6)
显然一个数组中的字符串是空的。 – Eran
@Eran是正确的。一个简单的解决方法是使用'word.endsWith(“y”)|| word.endsWith( “Z”)'。这也适用于空字符串(如预期的那样产生错误)。 –