java - 为什么这个程序给我一个数组索引越界异常?

标签 java while-loop indexoutofboundsexception

static char characters[] = { 'a', 'b', ' ', 'c', ' ', 'e', 'f', ' ' };

public static void main(String args[]) {

    for (int i = 0; i < characters.length; i++) {
        int j = i + 1;

        if (characters[i] == ' ') {
            while (j < characters.length && characters[j] == ' ' || characters[j] == '\u0000') {
                j++;  // increment j till a non-space char is found
            }
        }
    }

    for (char character : characters) {
        System.out.print(character + " ");
    }
}

Eclipse 显示以下错误: 线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 8 在loopchecker.main(loopchecker.java:13)

第 13 行是 while 循环。但我已经在检查 j's 值是否小于长度。

最佳答案

这是因为 or 运算符。

下面的条件是这样的

(j < characters.length && characters[j] == ' ') || characters[j] == '\u0000'

因此,由于 and 运算符的优先级高于 or 运算符,因此您始终执行 or 条件,这会导致 ArrayOutOfBoundException。 您可能会想要在 while 条件中包含大括号。

while (j < characters.length && (characters[j] == ' ' || characters[j] == '\u0000'))

关于java - 为什么这个程序给我一个数组索引越界异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35570434/

相关文章:

java - 如何在java中返回一个 boolean 方法?

java - java中for循环中的越界异常打印小于数组列表大小

java - 寻找整数的因数

java - 在数组中的特定索引处插入项目 - IndexOutOfBounds 异常

尝试在服务器上上传文件时出现 java.lang.IndexOutOfBoundsException

java - Android SMS BroadcastReceiver NullPointer

java - 使用返回 `java.io.InputStream` 的可靠超时读取 http 页面的类

Java replaceAll 用正则表达式

python - 为什么我的 while 循环出现值错误?

java - JAVA/J2EE 中的组合生成器