有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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;

}

共 (5) 个答案

  1. # 1 楼答案

    but I do not understand how the !found part can be compared with a < sign.

    从…的优先顺序开始!运营商超过&&;运算符,首先对find的值求反,然后将索引的值和accounts数组的长度与<;操作人员这样想:

    (!found) && (index < accounts.length)
    
  2. # 2 楼答案

    您的方法在accounts数组中查找int input。如果在循环中断时找到与input相同的值,则方法返回true

    while语句说:循环直到found为假,并且index小于accounts.length

  3. # 3 楼答案

    The way my brain interprets this is as "while found is not false AND index is smaller than the length of the accounts array"

    你的大脑应该将其解释为“while found不是真的,索引小于accounts数组的长度”

    当搜索了accounts的所有元素或找到了匹配的帐户时,while循环结束

  4. # 4 楼答案

    !found指一个布尔值,设置为false

    因此,在括号中,我们有“not false AND index小于accounts数组的长度”

    这相当于“true且索引长度小于accounts数组”

    索引设置为一个值,例如开始时为0。假设accounts数组的长度为5。然后我们得到“0小于5”。该语句在数学上为真,因此计算结果为布尔真

    然后,我们的陈述被简化为“真与真”,这在逻辑上是正确的。在while循环的上下文中,我们有while (true),它本身将执行while循环

    希望这有帮助,如果你需要进一步的澄清,请告诉我

  5. # 5 楼答案

    <不适用于!found,它只适用于indexaccounts.length()!foundindex < accounts.length是两种不同的独立条件。两者都必须为true,循环才能运行。如果这有助于你理解的话,你可以这样写

     while ((!found) && (index < accounts.length)) {
    

    这句话说明了两件事:

    1. while found不是true(found保留true的值,但它被!否定)

    1. index小于accounts.length(但是accounts数组中有许多成员)

    然后它将执行支架内受控块中的任何内容