Java:不理解这种“while”条件
我有一个方法,它接受一个输入数字,并将其与整数数组中的数字进行比较,然后根据找到的值返回true或false。该方法工作正常,但我在解释其中的一行代码时遇到问题。特别是在while
语句(!found && index < accounts.length)
中。我的大脑将其解释为“whilefound不是假的,索引小于accounts数组的长度”。。。但是我不明白!found
部分如何与<
操作符相比较。完整的方法如下
public static boolean account(int input) {
// account array
int accounts[] = { 5658845, 4520125, 7895122, 8777541, 4581002 };
// Loop control variable
int index = 0;
// Search results
boolean found = false;
// Search the array.
while (!found && index < accounts.length) {
if (accounts[index] == input) {
found = true;
}
// Increment index
index++;
}
// Return result of search
return found;
}
# 1 楼答案
从…的优先顺序开始!运营商超过&&;运算符,首先对find的值求反,然后将索引的值和accounts数组的长度与<;操作人员这样想:
# 2 楼答案
您的方法在
accounts
数组中查找int input
。如果在循环中断时找到与input
相同的值,则方法返回truewhile语句说:循环直到
found
为假,并且index
小于accounts.length
# 3 楼答案
你的大脑应该将其解释为“while found不是真的,索引小于accounts数组的长度”
当搜索了
accounts
的所有元素或找到了匹配的帐户时,while循环结束# 4 楼答案
!found
指一个布尔值,设置为false
因此,在括号中,我们有“not false AND index小于accounts数组的长度”
这相当于“true且索引长度小于accounts数组”
索引设置为一个值,例如开始时为0。假设accounts数组的长度为5。然后我们得到“0小于5”。该语句在数学上为真,因此计算结果为布尔真
然后,我们的陈述被简化为“真与真”,这在逻辑上是正确的。在while循环的上下文中,我们有
while (true)
,它本身将执行while循环希望这有帮助,如果你需要进一步的澄清,请告诉我
# 5 楼答案
<
不适用于!found
,它只适用于index
和accounts.length()
!found
和index < accounts.length
是两种不同的独立条件。两者都必须为true,循环才能运行。如果这有助于你理解的话,你可以这样写这句话说明了两件事:
found
将保留true的值,但它被!
否定)及
index
小于accounts.length
(但是accounts
数组中有许多成员)然后它将执行支架内受控块中的任何内容