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

Write a Java program that outputs the difference between two lists of integers.

ID: 3827423 • Letter: W

Question

Write a Java program that outputs the difference between two lists of integers. When entering a list, the user first enters the number of elements in the list. Then, she inputs the integers in that list. After entering two list of integers, the program must output the integers that belong to the first but not the second list. The order of the integers in the difference output must be consistent with the order of the integers in the first list (for instance, the difference in the first sample run is {2, 12, 4} not {12, 4, 2} nor {2, 4, 12}). Please see the below sample runs and be consistent with the output format.

Sample Runs. Enter the number of integers in the first list: Enter the integers in the first list: Enter the number of integers in the second list: Enter the integers in the second list: 11 34 The difference is 2 12 4 Enter the number of integers in the first list: Enter the integers in the first list: 21 Enter the number of integers in the second list: Enter the integers in the second list: 21 33 The difference is f

Explanation / Answer

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class ListDifference {
public static void main(String[] args)
{
int n1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of integers in the first list: ");
n1 = sc.nextInt();
System.out.println("Enter the integers in the first list:");
List<Integer> list1 = new ArrayList<>(n1);
for(int i = 0; i < n1; i++)
{
list1.add(sc.nextInt());
}
  
System.out.println("Enter the number of integers in the second list: ");
n1 = sc.nextInt();
System.out.println("Enter the integers in the second list:");
List<Integer> list2 = new ArrayList<>(n1);
for(int i = 0; i < n1; i++)
{
list2.add(sc.nextInt());
}
  
  
List<Integer> diff = new ArrayList<>();
for(Integer i : list1)
{
if (!list2.contains(i))
{
diff.add(i);
}
}
System.out.print("The difference is {");
if (diff.size() > 0)
{
System.out.print(diff.get(0));
}
for(int i = 1; i < diff.size(); i++)
{
System.out.print(", " + diff.get(i));
}
System.out.println("}.");
sc.close();
}
}

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