You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 08:22:06