java如何在数组中查找指定元素

   2024-10-20 5970
核心提示:在Java中,可以使用循环遍历数组来查找指定的元素。以下是一个简单的示例:public class Main {public static void main(String[

在Java中,可以使用循环遍历数组来查找指定的元素。以下是一个简单的示例:

public class Main {    public static void main(String[] args) {        int[] arr = {1, 2, 3, 4, 5};        int target = 3;                boolean found = false;        for (int i = 0; i < arr.length; i++) {            if (arr[i] == target) {                found = true;                break;            }        }                if (found) {            System.out.println("Element " + target + " found in the array.");        } else {            System.out.println("Element " + target + " not found in the array.");        }    }}

这段代码会在数组 arr 中查找元素 target,如果找到则输出找到的信息,如果没有找到则输出未找到的信息。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号