繁体   English   中英

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

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

我正在尝试在用户输入一些数字时打印非重复值,它应该显示不重复的数字。 我正在获取所有值,我的程序如下

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]);
    }       
}
}

您只需要更改两件事:

  1. 检查整个阵列是否重复。 int j = 0而不是int j = i
  2. 不要将值与其自身进行比较。 && i != j添加到您的if条件中。

现在您的代码可以使用了。

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

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

使用HashSet怎么样?

它仅包含非重复值。

代替boolean foundboolean found ,采用int count=0来对数字进行计数并打印count == 1的数字

如图所示,相应地更改代码

  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]);
} 

输入:
1个
2
2
3
3
4
5

输出:
1个
4
5

您可以使用计数值的映射来更快地完成此操作:

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