w3resource

Java: Check if an array of integers contains two specified elements

Java Array: Exercise-32 with Solution

Write a Java program to check if an array of integers contains two specified elements 65 and 77.

Pictorial Presentation:

Java Array Exercises: Check if an array of integers contains two specified elements

Sample Solution:

Java Code:

// Import the java.util package to use utility classes, including Arrays.
import java.util.*;

// Import the java.io package to use input and output classes.
import java.io.*;

// Define a class named Exercise32.
public class Exercise32 {
    // The main method for executing the program.
    public static void main(String[] args) {
        // Declare and initialize an array of integers.
        int[] array_nums = {77, 77, 65, 65, 65, 77};

        // Print the original array.
        System.out.println("Original Array: " + Arrays.toString(array_nums));

        // Define two numbers to be checked in the array.
        int num1 = 77;
        int num2 = 65;

        // Call the result method with the array and two numbers as arguments and print the result.
        System.out.println("Result: " + result(array_nums, num1, num2));
    }	

    // Define a method named result that takes an array of integers and two numbers as inputs.
    public static boolean result(int[] array_nums, int num1, int num2) {
        // Use an enhanced for loop to iterate through the array elements.
        for (int number : array_nums) {
            // Check if the current number is not equal to num1 and not equal to num2.
            boolean r = number != num1 && number != num2;
            // If the condition is met, return false.
            if (r) {
                return false;
            }
        }
        // If all elements in the array are either num1 or num2, return true.
        return true;
    }
}

Sample Output:

                                                                              
Original Array: [77, 77, 65, 65, 65, 77]                               
Result: true

Flowchart:

Flowchart: Java exercises: Check if an array of integers contains two specified elements

Java Code Editor:

Previous: Write a Java program to check if the sum of all the 10's in the array is exactly 30.
Next: Write a Java program to remove the duplicate elements of a given array and return the new length of the array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-exercises/array/java-array-exercise-32.php