Java 尝试从控制台识别非重复值并将非重复值打印到输出

Java 尝试从控制台识别非重复值并将非重复值打印到输出,java,Java,我试图打印非重复值,当用户输入一些数字时,它应该显示不重复的数字。我得到了所有的值,我的程序如下 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

我试图打印非重复值,当用户输入一些数字时,它应该显示不重复的数字。我得到了所有的值,我的程序如下

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]);
    }       
}
}
公共类比较{
公共静态void main(字符串[]args){
扫描仪sc=新的扫描仪(System.in);
System.out.println(“输入字符串:”);
int[]数组=新的int[7];

对于(int i=0;i您只需更改两件事:

  • 检查整个数组是否存在重复项。
    int j=0
    而不是
    int j=i
  • 不要将值与自身进行比较。将
    &&i!=j
    添加到if条件中
  • 现在你的代码可以工作了

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

    输出:1,2,4,5,6使用怎么样


    它将只包含不重复的值。

    不是找到的
    布尔值
    ,而是使用
    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]);
    } 
    
    for(int i=0;i
    输入:
    1
    2
    2
    3
    3
    4
    五,

    输出:
    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);
              }
            }
         }       
    }
    
    公共类比较{
    公共静态void main(字符串[]args){
    扫描仪sc=新的扫描仪(System.in);
    System.out.println(“输入字符串:”);
    映射值=新的HashMap();
    
    对于(int i=0;i您可以使用
    Set
    存储整数并检查?如果输入3和3,哈希集存储3。但他不想输出一个重复的值。