IndexOutOfBoundsException而不是Ending Loop

时间:2015-10-29 20:41:55

标签: java while-loop indexoutofboundsexception

为什么

int row = 1;
// multiArray[col].length = 6

while(multiArray[col][row] > 1 && row < multiArray[col].length) {
    sum += multiArray[col][row];
    row++;
}

返回IndexOutOfBoundsException?

我认为如果行变为6,则while循环不会运行,而不是返回错误。

1 个答案:

答案 0 :(得分:2)

&&运算符是short-circuit operator。这意味着如果它可以告诉左操作数的结果,那么它就不会评估右侧。

切换操作数的顺序,因此首先进行入站检查,如果失败,则不会发生数组值检查,如果进行了评估,则会抛出异常。

while(row < multiArray[col].length && multiArray[col][row] > 1) {
相关问题