Advertisement
dimipan80

9. Combine Lists of Letters

Sep 13th, 2014
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.52 KB | None | 0 0
  1. /* Write a program that reads two lists of letters l1 and l2 and combines them:
  2.  * appends all letters c from l2 to the end of l1, but only when c does not appear in l1.
  3.  * Print the obtained combined list. All lists are given as sequence
  4.  * of letters separated by a single space, each at a separate line.
  5.  * Use ArrayList<Character> of chars to keep the input and output lists. */
  6.  
  7. import java.util.ArrayList;
  8. import java.util.Scanner;
  9.  
  10. public class _09_CombineListsOfLetters {
  11.  
  12.     public static void main(String[] args) {
  13.         // TODO Auto-generated method stub
  14.         Scanner scan = new Scanner(System.in);
  15.         System.out.println("Enter sequence of letters to the First list on single line, separated by a space:");
  16.         String firstLine = scan.nextLine();
  17.         System.out.println("Enter sequence of letters to the Second list on single line, separated by a space:");
  18.         String secondLine = scan.nextLine();
  19.  
  20.         String[] firstArr = firstLine.split("[^a-zA-Z]");
  21.         String[] secondArr = secondLine.split("[^a-zA-Z]");
  22.  
  23.         ArrayList<Character> combinedList = new ArrayList<>();
  24.         ArrayList<Character> secondList = new ArrayList<>();
  25.         for (int i = 0; i < firstArr.length; i++) {
  26.             char letter = firstArr[i].charAt(0);
  27.             combinedList.add(letter);
  28.         }
  29.  
  30.         for (int i = 0; i < secondArr.length; i++) {
  31.             char letter = secondArr[i].charAt(0);
  32.             if (!combinedList.contains(letter)) {
  33.                 secondList.add(letter);
  34.             }
  35.         }
  36.  
  37.         combinedList.addAll(secondList);
  38.         System.out.println("The obtained combined list is:\n" + combinedList);
  39.     }
  40.  
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement