2016-12-13 39 views
0

我试图解决编码蝙蝠的问题并且无法通过一项测试。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)

+2

显然一个数组中的字符串是空的。 – Eran

+0

@Eran是正确的。一个简单的解决方法是使用'word.endsWith(“y”)|| word.endsWith( “Z”)'。这也适用于空字符串(如预期的那样产生错误)。 –

回答

1

Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:6)意味着你打电话第3210指数。

你打电话总是charAt(word.length()-1)所以如果word.length()-1 == -1,word.length() == 0。在检查最后一封信前检查是否加入word.length()>0

它由以下切片造成的:

!!day--yaz!! 
["day", "yaz", ""] 

例如,你可以这样写:

for (String word : newArr) { 
    if (word.length() > 0 && (word.charAt(word.length() - 1) == 'y' || 
    word.charAt(word.length() - 1) == 'z')) { 
    count++; 
    } 
    } 
    return count; 
} 

或简单(根据Ole的想法):

for (String word : newArr) { 
    if (word.endsWith("y") || word.endsWith("z")) { 
    count++; 
    } 
    } 
    return count; 
} 
相关问题