Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program named CommonElements that prompts the user to enter two arrays o

ID: 3704600 • Letter: W

Question

Write a program named CommonElements that prompts the user to enter two arrays of integers, saves the common elements that appear in both arrays in an ArrayList and displays the contents of the ArrayList. Note that the first number in the input indicates the number of the elements in the array. This number is not part of the array. Here are several sample run:

Enter list1: 5 5 10 2 1 6

Enter list2: 9 2 3 10 3 34 35 67 3 1

The common elements are 10 2 1

Enter list1: 7 1 2 3 4 5 6 7

Enter list2: 5 10 11 12 13 14 15

There are no common elements

Make sure the program follows the Java Coding Guidelines with comments documenting the codes.

Explanation / Answer

import java.util.Scanner;//importing Scanner class

public class CommonElements {// class name CommonElements

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int n, m, k;

k = 0;//counter for Arraylist

System.out.print("Enter list1:");

n = sc.nextInt();//taking input from keyboard for list1 array size

int a[] = new int[n];//declaring array a

for (int i = 0; i < n; i++) {//for loop for inserting values in array a

a[i] = sc.nextInt();

}

System.out.print("Enter list2:");

m = sc.nextInt();//getting size of second list or array b

int b[] = new int[m];//declaring array b

int Arraylist[] = new int[m + n];//declaring Array Arraylist

for (int i = 0; i < m; i++) {//for loop for inserting values in array b

b[i] = sc.nextInt();

}

for (int i = 0; i < n; i++) {//loop for checking common elements

for (int j = 0; j < m; j++) {

if (a[i] == b[j]) {

Arraylist[k] = a[i];

k++;

}

}

}

System.out.println("comman elements are:");

for (int i = 0; i < k; i++) {//printing common elements

System.out.println(Arraylist[i]);

}

if(k==0)//if no common elements then prints below statement

{

System.out.print("there are no common elements");

}

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote