settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Combine Lists of Letters - Java Task

+7 votes

Write a program that reads two lists of letters l1 and l2 and combines them: appends all letters c from l2 to the end of l1, but only when c does not appear in l1. Print the obtained combined list. All lists are given as sequence of letters separated by a single space, each at a separate line. Use ArrayList<Character> of chars to keep the input and output lists.

Examples:

combine list of letters in java

asked in Java category by user hues
edited by user golearnweb

2 Answers

+1 vote
 
Best answer

Here's my solution - with 3rd list:

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

public class Pr_07_Upr {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        char[] l1In = scanner.nextLine().toCharArray();
        ArrayList<Character> l1 = new ArrayList<>();

        for (int i = 0; i < l1In.length; i++) {
            l1.add(l1In[i]);
        }

        char[] l2ln = scanner.nextLine().toCharArray();
        ArrayList<Character> l2 = new ArrayList<>();

        for (int i = 0; i < l2ln.length; i++) {
            l2.add(l2ln[i]);
        }

        ArrayList<Character> outputList = l1;

        for (int i = 0; i < l2.size(); i++) {
            if (!l1.contains(l2.get(i))) {
                outputList.add(' ');
                outputList.add(l2.get(i));
            }
        }

        for (int i = 0; i < outputList.size(); i++) {
            System.out.print(outputList.get(i));
        }
    }
}

 

answered by user richard8502
selected by user golearnweb
+1 vote

Here's my solution:

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

public class Pr_07_CombineListsOfLetters {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        char[] l1Array = scanner.nextLine().toCharArray();
        ArrayList<Character> l1 = new ArrayList<>();

        for (int i = 0; i < l1Array.length; i++) {
            l1.add(l1Array[i]);
        }

        char[] l2Array = scanner.nextLine().toCharArray();
        ArrayList<Character> l2 = new ArrayList<>();

        for (int i = 0; i < l2Array.length; i++) {
            l2.add(l2Array[i]);
        }

        for (int i = 0; i < l1.size(); i++) {
            for (int j = 0; j < l2.size(); j++) {
                if (!l1.contains(l2.get(j))) {
                    l1.add(' ');
                    l1.add(l2.get(j));
                }
            }
        }

        for (int i = 0; i < l1.size(); i++) {
            System.out.print(l1.get(i));
        }
    }
}

 

answered by user john7
...