Write a class ElementCheckInEveryPair with a public method checkElement that takes two parameters one is arr of type int[] and second one is arg of type int and returns true if every pair of arr contains at least one arg.
Assumptions:
- arr is never null
These are examples for your understanding:
Enter no of elements in the array: 6 Enter elements in the array seperated by space: 52 2 3 2 65 2 Enter the search element: 2 true
Enter no of elements in the array: 6 Enter elements in the array seperated by space: 4 5 4 1 1 4 Enter the search element: 4 false
Expected Output:
Enter·no·of·elements·in·the·array: 7 Enter·elements·in·the·array·seperated·by·space: 1 2 3 2 2 4 2 Enter·the·search·element: 2 true
Expected Output:
Enter·no·of·elements·in·the·array: 6 Enter·elements·in·the·array·seperated·by·space: 1 2 2 1 1 2 Enter·the·search·element: 2 false
Solution
import java.util.Scanner;
public class ElementCheckInEveryPairMain{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter no of elements in the array:");
int n = s.nextInt();
int[] arr = new int[n];
System.out.println("Enter elements in the array seperated by space:");
for(int i = 0; i < n; i++)
{
arr[i] = s.nextInt();
}
System.out.println("Enter the search element:");
int arg = s.nextInt();
ElementCheckInEveryPair eleCheck = new ElementCheckInEveryPair();
boolean result = eleCheck.checkElement(arr, arg);
System.out.println(result);
}
public boolean checkElement(int[] arr, int arg) {
//Write your code here
int size = arr.length;
boolean result = false;
for(int i = 0; i < size; i++){
if(arr[i]==arg || arr[i+1]==arg){
result=true;
} else if(arr[i]!=arg || arr[i+1]!=arg){
result=false;
break;
}
}
return result;
}
}
Happy Learning – If you require any further information, feel free to contact me.