1.3k views
3 votes
Using Eclipse, create a New Java project named YourNameCh20Project-- for example, I would name my Project YourNameCh20Project

Create a new class named YourInitialsCh20App. – for example, I would name my class YNCh20App.
Write a program that prompts the user to enter two lines of words. The words are separated by spaces. Extract the words from the two lines into two lists. Display the union, difference, and intersection of the two lists in ascending alphabetical order.
Here is a sample run:
Enter the first line: red green blue yellow purple cyan orange
Enter the second line: red black brown cyan orange pink
The union is [black, blue, brown, cyan, cyan, green, orange, orange, pink, purple, red, red, yellow]
The difference is [blue, green, purple, yellow]
The intersection is [cyan, orange, red]
Your name must be displayed on line 1 of the class.
All variables must begin with your initials in camelCasing. For example, I would name my variables ynInput, ynLine1, ynLine2, ynWords, ynList1, ynList2, ynTemp
Hint: You will use an Arrays, ArrayLists , and List

1 Answer

3 votes

Final answer:

To solve this problem, follow the steps in Eclipse to create a Java project and class. Prompt the user for two lines of words, split them into arrays, and store them in ArrayLists. Use ArrayList methods to calculate the union, difference, and intersection of the lists, then sort and display the results.

Step-by-step explanation:

To solve this problem, you can follow these steps in Eclipse:

  1. Create a new Java project named YourNameCh20Project.
  2. Create a new class named YourInitialsCh20App.
  3. Inside the main method of the class, prompt the user to enter two lines of words and store them in separate variables.
  4. Use the split() method to split the lines into arrays of words.
  5. Create two ArrayLists to store the words from each line.
  6. Loop through the arrays of words and add the words to the respective ArrayLists.
  7. Create a third ArrayList to store the union of the two lists of words. Use the addAll() method to add all the elements from the first list, then add only the unique elements from the second list.
  8. Create a fourth ArrayList to store the difference of the two lists of words. Use the removeAll() method to remove all the elements from the first list that are also present in the second list.
  9. Create a fifth ArrayList to store the intersection of the two lists of words. Use the retainAll() method to keep only the elements that are present in both lists.
  10. Sort all the ArrayLists in ascending alphabetical order using the sort() method.
  11. Finally, print out the union, difference, and intersection of the two lists.

User Mohamad Ibrahim
by
8.4k points