简体   繁体   中英

finding non repeating element.Code Does't print anything

I want to add the unique element in array A to the list L. This code doesn't print anything. Please tell me where i am going wrong.

    import java.util.*;

    public class Unique {
    public static void main(String[] args){


            List<Integer> L = new LinkedList<>();
            int[] A = {3,3,9,1,6,5,8,1,5,3};
            int[] B = {3,3,9,1,6,5,8,1,5,3};

            int count =0;
            //outer loop

            for(int i=0;i<A.length;i++){
            //inner loop
                for(int j=0;j<B.length;j++){
                    if(A[i]== B[j])count++;
                    }
                if(count==1) L.add(A[i]);
                }
            for(int i =0;i<L.size();i++){
                System.out.print(L.get(i)+" ");
            }
    }
}

Move the line below inside your inner loop:

 int count = 0;

Your final code will be:

    // outer loop
    for (int i = 0; i < A.length; i++) {
        int count = 0;

        // inner loop
        for (int j = 0; j < B.length; j++) {
            if (A[i] == B[j])
                count++;
        }
        if (count == 1)
            L.add(A[i]);
    }

Output

9 6 8 

Alternatively, you can write your code like this too:

    int count;

    // outer loop
    for (int i = 0; i < A.length; i++) {
        count = 0;

        // inner loop
        for (int j = 0; j < B.length; j++) {
            if (A[i] == B[j])
                count++;
        }
        if (count == 1)
            L.add(A[i]);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM