温馨提示×

java 数组中是否存在某个值

小亿
79
2024-01-10 15:54:45
栏目: 编程语言

在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的值来判断是否存在目标值。

0