简体   繁体   中英

Trying to Identify the non repeating values from the console and print the non-repeating values to output

I am trying to print the non repeated values when user enter some numbers it should display the numbers which are not duplicate. i am getting all the values and my program is as below

public class Compare {
public static void main(String[] args){
    Scanner sc= new Scanner(System.in);
    System.out.println("enter the string:");
            int[] array = new int[7];
            for (int i=0; i<array.length;i++) {
            array[i] = Integer.parseInt(sc.nextLine());
         } 
            for (int i = 0; i < array.length; i++) {
                boolean found = false;
                for (int j = i+1; j < array.length; j++)
                    if (array[i] == array[j]) {
                        found = true;
                      break;
                    }
               if(!found)
                System.out.println(array[i]);
    }       
}
}

You only have to change two things:

  1. Check the whole array for duplicates. int j = 0 instead of int j = i
  2. Don't compare the the value with itself. Add && i != j to your if condition.

Now your code will work.

Input: 1,2,3,3,4,5,6

Output: 1,2,4,5,6

How about using, HashSet ?

It will only contain non duplicate values.

Instead of boolean found , take a int count=0 for counting the numbers and print the numbers which have count == 1

Change the code accordingly as shown

  for (int i = 0; i < array.length; i++) {
            int count=0;
            for (int j = 0; j < array.length; j++)
                if (array[i] == array[j]) {
                    count++;
                }
           if(count==1)
            System.out.println(array[i]);
} 

Input:
1
2
2
3
3
4
5

Output:
1
4
5

You could do this quicker with a map counting the number of values:

public class Compare {
    public static void main(String[] args){
        Scanner sc= new Scanner(System.in);
        System.out.println("enter the string:");
        Map<int, int> values = new HashMap<int, int>();
        for (int i=0; i<7;i++) {
          value = Integer.parseInt(sc.nextLine());
          if (!values.contains(value)) {
              values.put(value, 1);
          } else {
              values.put(value, values.get(value) + 1);
          }
        }
        for (int value : values.keySet()) {
          if (values.get(value) == 1) {
            System.out.println(value);
          }
        }
     }       
}

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