Java中出现String Index Out Of Bounds Exception,请求排查解决
String索引越界异常的解决方法
问题出在循环条件上:
- Java中字符串的索引从0开始,最后一个字符的索引是
word.length() - 1。你写的循环条件是i <= word.length(),当i等于word.length()时,word.charAt(i)访问的是不存在的位置,直接触发StringIndexOutOfBoundsException。
修正后的代码如下:
int correctCount = 0; for (int i = 0; i < word.length(); i++) { if (playerGuesses.contains(word.charAt(i))) { System.out.print(word.charAt(i)); correctCount++; } else { System.out.print("-"); } } System.out.println(); return (word.length() == correctCount);
只需要把循环条件里的<=改成<,就能让循环遍历字符串的每一个有效字符,避免越界问题。
内容的提问来源于stack exchange,提问作者Sen Rai
相关产品推荐
相关产品推荐

