温馨提示×

java 数组中是否存在某个值

小亿
99
2024-01-10 15:54:45
栏目: 编程语言
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中,可以使用循环遍历数组来判断数组中是否存在某个值。下面是一个示例代码:

public class Main {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        int target = 3;
        boolean found = false;
        
        for (int i = 0; i < array.length; i++) {
            if (array[i] == target) {
                found = true;
                break;
            }
        }
        
        if (found) {
            System.out.println("数组中存在目标值" + target);
        } else {
            System.out.println("数组中不存在目标值" + target);
        }
    }
}

输出:

数组中存在目标值3

在上面的代码中,我们使用了一个布尔变量found来标记是否找到了目标值。在遍历数组的过程中,如果找到了目标值,将found设置为true并跳出循环。最后根据found的值来判断是否存在目标值。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:java怎么判断数组中是否存在某值

0