gpt4 book ai didi

java - 带有 3 个 "and"(&&) 运算符的 if 语句在重新排列时会导致错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:58:35 24 4
gpt4 key购买 nike

有人可以向我解释一下,为什么当我重新排列以下 if 语句中的条件时,它要么抛出 StringIndexOutOfBoundsException,要么不抛出;

public int matchUp(String[] a, String[] b) {
int count = 0;

for (int i = 0; i < a.length; i++) {
if (a[i].length() > 0 && b[i].length() > 0 &&
a[i].charAt(0) == b[i].charAt(0)) {
count++;
}
}
return count;
}

基本上我的问题是,这个 if 语句是怎样的

if (a[i].charAt(0) == b[i].charAt(0) &&
a[i].length() > 0 && b[i].length() > 0)

与此 if 语句不同

if (a[i].length() > 0 && b[i].length() > 0 &&
a[i].charAt(0) == b[i].charAt(0)) {
count++;
}

第一个抛出异常,例如:

matchUp(["", "", "ccc"], ["aa", "bb", "cc"]) → 1    

异常(exception):

java.lang.StringIndexOutOfBoundsException: String index out of range: 0 (line number:6)

最佳答案

Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 0 (line number:6)

表示您尝试访问空数组的索引 0。

另一件事是,当只有 expression1 为 false 时,表达式 expression1 && expression2 的计算结果为 false。没有尝试计算表达式2。

关于java - 带有 3 个 "and"(&&) 运算符的 if 语句在重新排列时会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41127891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com