简体   繁体   English

尝试从控制台中识别非重复值并打印非重复值以输出

[英]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 int j = 0而不是int j = i
  2. Don't compare the the value with itself. 不要将值与其自身进行比较。 Add && i != j to your if condition. && i != j添加到您的if条件中。

Now your code will work. 现在您的代码可以使用了。

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

Output: 1,2,4,5,6 输出:1,2,4,5,6

How about using, HashSet ? 使用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 代替boolean foundboolean found ,采用int count=0来对数字进行计数并打印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 1个
2 2
2 2
3 3
3 3
4 4
5 5

Output: 输出:
1 1个
4 4
5 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);
          }
        }
     }       
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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