英文:
Does order of the states in the if statement matter?
问题
从代码的第5行开始,代码如下:
if (i + 2 < str.length() && str.charAt(i) == 'y' && str.charAt(i + 2) == 'k')
语句的顺序是否重要?我在想,因为当我赋值 **str = "yak123ya"** 时,
`(i + 2 < str.length() && str.charAt(i) == 'y' && str.charAt(i + 2) == 'k')` 完全正常工作,
但是
`(str.charAt(i) == 'y' && str.charAt(i + 2) == 'k' && i + 2 < str.length())` 导致
错误
> StringIndexOutOfBoundsException: String index out of range: 8 (第5行)
以下是你提供的代码部分:
public String stringYak(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
if (i + 2 < str.length() && str.charAt(i) == 'y' && str.charAt(i + 2) == 'k') {
i += 2;
} else {
result += str.charAt(i);
}
}
return result;
}
谢谢!
英文:
from line 5 on my code which is,
if (i + 2 < str.length() && str.charAt(i) == 'y' && str.charAt(i + 2) == 'k')
Does the order of statements matter? I was wondering because
when I assign str = "yak123ya"
(i + 2 < str.length() && str.charAt(i) == 'y' && str.charAt(i + 2) == 'k')
works perfectly fine
but
(str.charAt(i) == 'y' && str.charAt(i + 2) == 'k' && i + 2 < str.length())
causes
error
> StringIndexOutOfBoundsException: String index out of range: 8 (line:5)
public String stringYak(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
if (i + 2 < str.length() && str.charAt(i) == 'y' && str.charAt(i + 2) == 'k') {
i += 2;
} else {
result += str.charAt(i);
}
}
return result;
}
Thank you!!
答案1
得分: 4
表达式从左到右进行求值,采用短路求值。这意味着当求值表达式 a && b
时,若 a
求值为 false
,整个表达式求值为 false
,而不会执行 b
。
在这种情况下,当 i = 6
时,i + 2 < str.length()
为 false
,因此不会执行 charAt(6)
(也因此不会引发异常)。
英文:
The expressions are evaluated left to right, with short-circuiting. That means when an expression a && b
is evaluated, and a
evaluates to false
, the whole expression evaluates to false
without executing b
.
In this case, when i = 6
, i + 2 < str.length()
is false
, and therefore the charAt(6)
is not executed (and therefore not throwing an exception).
答案2
得分: 2
是的,当然,顺序很重要。就像在这个 if 语句中:
(i + 2 < str.length() && str.charAt(i) == 'y' && str.charAt(i + 2) == 'k')
如果第一个条件即 i + 2 < str.length() 为假,它将不会检查第二个条件即 str.charAt(i) == 'y',因此不会抛出 StringIndexOutOfBoundsException。
英文:
yes for sure order matters. as in this if statement
(i + 2 < str.length() && str.charAt(i) == 'y' && str.charAt(i + 2) == 'k')
if the first condition which is i + 2 < str.length() is false, it will not check the second condition which is str.charAt(i) == 'y' so it will not throw StringIndexOutOfBoundsException
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论