java - 为什么在这个数组的线性搜索的 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");
}
}
解决方案
只要您确保在索引达到数组的限制时跳出循环,您的代码也可以工作。有很多方法可以理解这一点。
//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;
}
``
推荐阅读
- xcode - 将环境变量传递给 XCode 构建
- javascript - Selenium WebDriver 等待 javascript 生成的表正在加载/可见
- python - Python 正则表达式 - 组
- sql - 创建 SQL 视图并从结果中删除数字 + 和 ()
- reactjs - React Hook 表单 - 控制器:从 v5 迁移到 v6
- spring - 我的 Spring Boot Web 应用程序启动但没有工作?
- java - ManyToOne 在创建 spring boot hiernate jpa 的两个表上给出 null
- javascript - 我尝试安装快速生成器,但出现此错误
- javascript - 如何使用反应路由器链接组件重新加载页面?
- java - 为什么 JVM tableswitch/lookupswitch 指令的格式有 0 到 3 个字节的填充?