首页 > 解决方案 > 为什么在这个数组的线性搜索的 while 循环条件中需要 !found 而不是 found ?

问题描述

我刚开始使用Java,并且对数组的线性搜索有一个非常愚蠢的问题。为什么有必要放置!found而不只是found放在while循环条件中?我有点困惑,因为在我看来,while循环应该在我们没有找到目标并且索引小于数组长度时运行,所以应该while((found)&&(index<myArray.length))改为?

public class LinearSearch {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int target = 2;
        boolean found = false;
        int index = 0;
        int indexOfTarget = -1;
        int [] myArray = {18,38,2,20,24,14,5};
        while ((!found)&&(index<myArray.length)) {
            if (myArray[index]==target) {
                indexOfTarget=index;
                found = true;
            }
            index++;
        }
        if(found) System.out.println("Found element at position "+indexOfTarget);
        else System.out.println("Target not found");
    }

}

标签: java

解决方案


只要您确保在索引达到数组的限制时跳出循环,您的代码也可以工作。有很多方法可以理解这一点。

//using !found, you need to break 
while (!found) {
   if (myArray[index]==target) {
       indexOfTarget=index;
       found = true;
       break;//also break when you find a match
   }
   index++;
   if (index == myArray.length) break;
}
``


推荐阅读