0

I want to get the common values of list1 and compare it to list2. I got an output of 11121 instead of 121. How can I resolve this?

Here's my code:

public class TwoLists {

    static void arrs() {
        int[] list1 = {1, 6, 2, 1, 4, 1, 2, 1, 8};
        int[] list2 = {1, 2, 1};
    
        for(int i = 0; i < list1.length-1; i++)
        {
            for(int o = i+3; o < list1.length; o++)
            {
                for(int out1 = list1[i]; out1 == list1[o]; out1++)
                {
                    System.out.print(out1);
                    }
                }
            }
        }


    public static void main(String[] args)
    {
        arrs();
    }

}
andrbrue
  • 721
  • 6
  • 15
  • 1
    I do not understand what you want to do. Maybe add some expected input and output? Also, list2 is never used in your code, is this correct? – andrbrue Oct 02 '20 at 23:22
  • Does this answer your question? [finding common elements in two integer arrays java](https://stackoverflow.com/questions/40632887/finding-common-elements-in-two-integer-arrays-java) – Spectric Oct 02 '20 at 23:25
  • Oh, I forgot. I stuck at list1 first :/ – NoviceProgrammer Oct 02 '20 at 23:25

1 Answers1

0

Try the following:

  • Use a Set<Integer> to record those already found.
  • then use a nested array going from start to finish for each array
  • in the outer loop, see if set.contains() the current value.
  • if so, continue outer loop.
  • otherwise, compare inner and outer list values.
  • when a match is found, print it, add to the set, and then break out of the inner loop.
  • continue next value in outer loop.

There are other, faster ways using just sets exclusively but this would serve as a start.

WJS
  • 36,363
  • 4
  • 24
  • 39