에이바바
에이바바

Reputation: 1031

Printing distinct integers in an array

I'm trying to write a small program that prints out distinct numbers in an array. For example if a user enters 1,1,3,5,7,4,3 the program will only print out 1,3,5,7,4.

I'm getting an error on the else if line in the function checkDuplicate.

Here's my code so far:

import javax.swing.JOptionPane;

public static void main(String[] args) {
    int[] array = new int[10];
    for (int i=0; i<array.length;i++) {
        array[i] = Integer.parseInt(JOptionPane.showInputDialog("Please enter"
                                  + "an integer:"));
    }
    checkDuplicate (array);
}

public static int checkDuplicate(int array []) {
    for (int i = 0; i < array.length; i++) {
        boolean found = false;
        for (int j = 0; j < i; j++)
            if (array[i] == array[j]) {
                found = true;
                break;
            }
        if (!found)
            System.out.println(array[i]);
    }
    return 1;
}
}

Upvotes: 0

Views: 18226

Answers (8)

import java.util.Scanner; public class PrintDistinctNumbers {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    int [] numberArray = createArray();
    System.out.println("The number u entered are:   ");
    displayArray(numberArray);
    getDistinctNumbers(numberArray);
}

public static int[] createArray() {
    Scanner input = new Scanner(System.in);
    int [] numberCollection = new int [10];
    System.out.println("Enter 10 numbers");

    for(int i = 0; i < numberCollection.length; i++){
        numberCollection[i] = input.nextInt();
    }
    return numberCollection;

}

public static void displayArray(int[] numberArray) {
    for(int i = 0; i < numberArray.length; i++){
        System.out.print(numberArray[i]+" ");
    }
}

public static void getDistinctNumbers(int[] numberArray) {
    boolean isDistinct = true;
    int temp = 0;
    int [] distinctArrayNumbers = new int [10];
    for ( int i = 0; i < numberArray.length; i++){
        isDistinct = true;
            temp = numberArray[i];

            for( int j = 0; j < distinctArrayNumbers.length; j++){
                if( numberArray[i] == distinctArrayNumbers[j] ){
                isDistinct = false;
            }


           }
            if(isDistinct){
                    distinctArrayNumbers[temp]=numberArray[i];
                    temp++;
                }


    }
    displayDistinctArray(distinctArrayNumbers);
}

public static void displayDistinctArray(int[] distinctArrayNumbers) {
    for( int i = 0; i < distinctArrayNumbers.length; i++){
        if(distinctArrayNumbers[i] != 0){
        System.out.println(distinctArrayNumbers[i]);
        }
    }
}

}

Upvotes: 0

monksy
monksy

Reputation: 14234

Either use a Set as other people have suggested or use an List compatible class. With a list compatible class just use the Contains method to check if it already exists in the array.

Upvotes: 1

javashlook
javashlook

Reputation: 10471

What you want can be accomplished using Java collection API, but not exactly as an one-liner, due to fact collection methods work with Objects and not primitives. J2SE lacks methods that convert, say, int[] to Integer[], but Apache Commons Lang library contains such useful methods, like ArrayUtils.toObject() and ArrayUtils.toPrimitive().

Using them, method to remove duplicated elements from an integer array looks something like this:

public static int[] removeDuplicates(int... array) {
    Integer[] ints = ArrayUtils.toObject(array);
    Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(ints));
    return ArrayUtils.toPrimitive(set.toArray(new Integer[set.size()]));
}

If your application is likely to include more of array/collection manipulation, I suggest you take a look at that library, instead of implementing things from scratch. But, if you're doing it for learning purposes, code away!

Upvotes: 2

MartinStettner
MartinStettner

Reputation: 29164

First of all, the "else if" statement is incorrect, since you don't provide any condition to the if (if you want an if, you need to write "if (condition) ...").

Second, you cannot decide inside the inner loop, if a value should be printed: The way your code works you write a value array[i] for each value array[j] that is different from array[i]!

Third: the inner loop needs only to go from 0 to the outer index i-1: For each element, you need only to decide, if it is the first occurrence (i.e. if the same value occured at any previous index or not). If it is, print it out, if not, ignore it.

A proper implementation of CheckDuplicate() would be:

public static void checkDuplicate(int array []) {
  for (int i = 0; i < array.length; i++) {
    boolean found = false;
    for (int j = 0; j < i; j++)
      if (array[i] == array[j]) {
        found = true;
        break;
      }
    if (!found)
      System.out.println(array[i]);
  }
}

But of course, some kind of Set would be much more efficient for bigger arrays...


EDIT: Of course, mmyers (see comments) is right by saying, that since CheckDuplicate() doesn't return any value, it should have return type void (instead of int). I corrected this in the above code...

Upvotes: 4

Nikhil
Nikhil

Reputation: 5771

Put them in a set ordered by insertion time, then convert back to an array if necessary.

new LinkedHashSet<Integer>(array).toArray()

Upvotes: 3

Bill the Lizard
Bill the Lizard

Reputation: 405745

It would probably be better to add each number to a Set implementation rather than an array. Sets are specifically for storing collections of elements where you want to filter out duplicates.

Upvotes: 1

Kevin Crowell
Kevin Crowell

Reputation: 10180

Try throwing all of the integers into a Set. Duplicates will not ever be added to the Set and you will be left will a set of unique integers.

Upvotes: 2

jjnguy
jjnguy

Reputation: 138864

The simplest way would be to add all of the elements to a Set<Integer> and then just print the contents of the Set.

Upvotes: 10

Related Questions