1. Introduction
In Java, checking if an array contains a certain value can be essential for various applications. There are multiple ways to achieve this, such as using a simple loop to traverse the array, or using Java’s built-in methods. In this post, we will demonstrate how to check if an array contains a specific value.
2. Program Steps
1. Define and initialize an array.
2. Define the value to be searched within the array.
3. Traverse the array and check if any element in the array is equal to the specified value.
3. Code Program
public class CheckArrayContainsValue {
public static void main(String[] args) {
// Step 1: Define and initialize an array
int[] array = {10, 20, 30, 40, 50};
// Step 2: Define the value to be searched within the array
int valueToCheck = 30;
// Step 3: Traverse the array and check if any element in the array is equal to the specified value
boolean contains = false;
for (int element : array) {
if (element == valueToCheck) {
contains = true;
break;
}
}
// Printing the result
if (contains) {
System.out.println("The array contains the value: " + valueToCheck);
} else {
System.out.println("The array does not contain the value: " + valueToCheck);
}
}
}
Output:
The array contains the value: 30
4. Step By Step Explanation
In Step 1, we define and initialize an integer array array with some elements.
In Step 2, we define the integer valueToCheck which we will search for in the array.
In Step 3, we traverse the array using a for-each loop and check each element to see if it is equal to valueToCheck. If we find the value, we set the boolean variable contains to true and break out of the loop.
Finally, we print whether the array contains the specified value or not based on the contains variable.