Java 中的字符串索引越界异常。我不知道该怎么办[重复]

问题描述 投票:0回答:3

我不明白为什么它一直给我字符串索引越界异常。

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);
java indexoutofboundsexception
3个回答
2
投票

数组从第 0 个索引开始,因此当您尝试在此处获取列表长度的索引

int i = 0; i <= word.length();i++
时,您超出了 1 个插槽。

这应该有效:

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

0
投票

String / Char 数组是从零开始的。

HelloWorld 是 10 个字符,但作为一个数组,我们将其视为:

H,e,l,l,o,W,o,r,l,d
0,1,2,3,4,5,6,7,8,9

每个角色都成为循环的迭代。

当您使用

i = 0; i <= word.length
时,它与
i <= 10
相同。

由于数组是从零开始的,当我们只有 10 个时,“小于或等于”实际上创建了循环的 11 次迭代。我们只有 10 个字符或迭代,我们不能有 11。第一个迭代值是“H " 在数组位置 0

str[0]
因此声明
i = 0;

迭代 10 时数组位置 9

str[9]
的最后一个值为“d”。位置 10,在迭代 11 时,
str[10]
不存在。它超出了数组的范围。

您实际上想要

i < 10
,这将是
i < word.length
。同样,我们想在 10 减 1 处停止,因为数组是从零开始的。


0
投票

是的,Java 使用从零开始的数组,这意味着当

i == word.length()
时,
i
超出了从
word.length()
中检索到的值的范围。所以你应该在
<
循环中使用小于号(
for
),而不是小于或等于(
<=
)。

for (int i = 0; i < word.length(); i++) {

此外,我强烈建议不要使用单字母变量名。这是忘记什么是什么的好方法。

© www.soinside.com 2019 - 2024. All rights reserved.