Java: Finding duplicate in array

I need to implement a duplicate search method in my program, but getting errors. If I comment out the duplicate search part, the program runs fine.

Error (I commented out the duplicate search part):

  do{ 
   System.out.print("Please enter an integer or -1 to stop: ");
   input=Integer.parseInt(scan.nextLine()); //parse library function 
   /** 
    * for(int i=0; i<A.length; i++){
    *     for(int j=i+1; j<A.length; j++{
    *         if(A[i].equals(A[j]))
    *         System.out.println("Duplicate input. Please enter another 
                          value: ");
    *         }
    *       }
    */
   if(input != -1) //if input is 
   Display.userInput(input);
}
while(input != -1); 

2 answers

  • answered 2018-10-22 16:52 Aagam Jain

    Try this.

    do{ 
       System.out.print("Please enter an integer or -1 to stop: ");
       input=Integer.parseInt(scan.nextLine());
       boolean flag = true;
       for(int i=0; i<A.length; i++){ 
          if(A[i].equals(input)) {
              System.out.println("Duplicate input. Please enter another value: ");
              flag = false;
              break;
          }
       }
       if(!flag) {
          continue;
       }
       if(input != -1) //if input is 
       Display.userInput(input);
    }
    
    while(input != -1); 
    

  • answered 2018-10-22 16:56 Ilya

        int A[] = {1, 5, 9, 5, 6};
        if (Arrays.stream(A).boxed()
                .collect(Collectors.groupingBy(Function.identity()))
                .entrySet()
                .stream()
                .map(Map.Entry::getValue)
                .map(Collection::size)
                .anyMatch(s -> s > 1)) {
            System.out.println("Duplicate input. Please enter another value:");
        }