2016-12-13 12 views
0

私はバットをコーディングする際の問題を解決しようとしており、1回のテストに合格できません。StringIndexOutOfBoundsException - 単語の最後の文字をチェックするときに-1を返します。

「y」または「z」で終わる単語の数を数えます。「y」は「重」で、「z」は「fez」の数ですが、 「黄色」(大文字小文字は区別されません)。単語の後ろにアルファベット文字がない場合、yまたはzは単語の最後にあると言います。私はこのテストに合格することはできませんしかし

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; 
} 

、それはこのエラーを示しています:(注:Character.isLetter(文字)のテストをcharがアルファベットの場合)ここで

は私のコードです

countYZ( "!!日 - YAZ !!")2

Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:6)

+2

1あなたの配列の中の文字列は空です。 – Eran

+0

@Eranが正しいです。簡単な修正は 'word.endsWith(" y ")|| word.endsWith( "z") '。これは空の単語列に対しても機能します(期待どおりにfalseを返します)。 –

答えて

1

Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:6)→あなたはを呼び出していることを意味し3210番目のインデックス。

word.length()-1 == -1word.length() == 0の場合は、常にcharAt(word.length()-1)と表示されます。最後の文字を確認する前に、word.length()>0の場合は小切手を追加してください。

これは、次のスライスによって引き起こされます:あなたが書くことができます例えば

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

Oleさんの考えによれば)
for (String word : newArr) { 
    if (word.length() > 0 && (word.charAt(word.length() - 1) == 'y' || 
    word.charAt(word.length() - 1) == 'z')) { 
    count++; 
    } 
    } 
    return count; 
} 

または単純:

for (String word : newArr) { 
    if (word.endsWith("y") || word.endsWith("z")) { 
    count++; 
    } 
    } 
    return count; 
} 
明らか
関連する問題