I'm trying to solve a problem on coding bat and cannot pass one test.
Given a string, count the number of words ending in 'y' or 'z' -- so the 'y' in "heavy" and the 'z' in "fez" count, but not the 'y' in "yellow" (not case sensitive). We'll say that ay or z is at the end of a word if there is not an alphabetic letter immediately following it. (Note: Character.isLetter(char) tests if a char is an alphabetic letter.)
Here is my code:
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;
}
However I cannot pass this test and it shows this error:
countYZ("!!day--yaz!!") → 2
Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:6)
Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:6)
means that you're calling -1
th index.
You're calling always charAt(word.length()-1)
so if word.length()-1 == -1
, word.length() == 0
. Add a check if word.length()>0
before checking last letter.
It's caused by the following slicing:
!!day--yaz!!
["day", "yaz", ""]
For example you can write:
for (String word : newArr) {
if (word.length() > 0 && (word.charAt(word.length() - 1) == 'y' ||
word.charAt(word.length() - 1) == 'z')) {
count++;
}
}
return count;
}
or simpler (according to Ole 's idea):
for (String word : newArr) {
if (word.endsWith("y") || word.endsWith("z")) {
count++;
}
}
return count;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.