Is there a particular value present in the Java array?

In Java, you can use a loop to iterate through an array to check if a certain value exists. Below is an example code:

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);
        }
    }
}

Output: Output:

数组中存在目标值3

In the code above, we utilized a boolean variable called found to indicate whether the target value was found. During the array traversal, if the target value was found, we set found to true and exited the loop. Finally, we checked the value of found to determine if the target value exists.

bannerAds