-5

I am in a beginning Java course. I created an array with length 10 using Scanner input. Now I need to write a program that checks to see if any of the elements in the array occur more than once. Guidance greatly appreciated!

  • Use any generic searching algorithm. – Munib Nov 11 '16 at 17:05
  • Welcome to stackoverflow. Please let us know what have you tried and where you are stuck. Although this question is very common, correct googling should def give you all the answers – Bhavik Patel Nov 11 '16 at 17:06
  • 1
    Please see: http://stackoverflow.com/questions/3951547/java-array-finding-duplicates – Tim Nov 11 '16 at 17:08
  • Loop through the elements of the array and compare each value with all the next ones. Come back with some code attempts. – sanastasiadis Nov 11 '16 at 17:12
  • This question is currently not answerable unless the asker tells us if its an array of primitive types (where you would need to compare with ==) or of objects like Strings (in which case equals should be used). – OH GOD SPIDERS Nov 11 '16 at 17:45

2 Answers2

1

Following code should do it.

import java.io.IOException;
import java.util.*;

public class test {
    public static void main(String [] args) throws IOException {

        Scanner scanner = new Scanner(System.in);

        int[] nums = new int[10];

        for (int i=0;i<10;i++) {
            nums[i] = scanner.nextInt();
        }

        System.out.println(findDuplicate(nums) ? "Duplicate found" : "No Duplicates");

    }

    public static boolean findDuplicate(int[] nums) {
        for (int i=0; i < 10; i++) {
            for (int j=0; j<10; j++) {
                if (i!=j && nums[i] == nums[j]) {
                    return true;
                }
            }
        }
        return false;
    }
}
dammina
  • 655
  • 1
  • 8
  • 23
0

you can use a nested loop like this

 for(int i=0;i<array.length;i++)
  {

     for(int j=i+1;j<array.length;j++)
      {
           if(array[i].equals(array[j]))
               {
                   System.out.println("Duplicate found");
               }

       }
     }
Raj Roy
  • 1
  • 1