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

Exercise 1: Write a program that reads words into two ArrayLists listl and list2

ID: 3726556 • Letter: E

Question

Exercise 1: Write a program that reads words into two ArrayLists listl and list2 and then creates a third ArrayList that contains words which are common to both list1 and list2. You may assume that the strings are entered as words separated by a space on a single line and the end is signaled by "-1" (String -1). You can use keyboardnext0 to read each word A sample dialog is shown below.- Enter words n one line , end with -I+' java c pascal ada java c++ -I+' Enter words n ne line , end with -I+' c pascal java lisp LARR-1 [java, c, pascal, ada, java, c++ [c, pascal, java, lisp, lispl Array List with common strings: [c, pascal, java]

Explanation / Answer

Hi.. I have written java program for the above.

Task1.java

import java.util.ArrayList;

import java.util.Scanner;

public class Task1 {

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner input = new Scanner(System.in);

String first="";

System.out.println("Enter words on one line, end with -1 ");

first = input.nextLine();

String second="";

System.out.println("Enter words on one line, end with -1 ");

second = input.nextLine();

ArrayList<String> list1 = new ArrayList<String>();

ArrayList<String> list2 = new ArrayList<String>();

ArrayList<String> list3 = new ArrayList<String>();

input = new Scanner(first);

while(input.hasNext()) {

String word = input.next();

if(!word.equalsIgnoreCase("-1")) {

if(!list1.contains(word))

list1.add(word);

}

}

input = new Scanner(second);

while(input.hasNext()) {

String word = input.next();

if(!word.equalsIgnoreCase("-1")) {

if(!list2.contains(word))

list2.add(word);

}

}

for(String s:list1) {

if(list2.contains(s)) {

list3.add(s);

}

}

System.out.println("List1 Items");

for(String s:list1) {

System.out.print(s+" ");

}

System.out.println(" List2 Items");

for(String s:list2) {

System.out.print(s+" ");

}

System.out.println(" Arraylist with common things");

for(String s:list3) {

System.out.print(s+" ");

}

}

}

Output:

Enter words on one line, end with -1
c java pascal java ada c++ -1
Enter words on one line, end with -1
pascal java ada lisp -1
List1 Items
c java pascal ada c++
List2 Items
pascal java ada lisp
Arraylist with common things
java pascal ada

Please test the code and let me know any querries. Thank you. All the best.