0

i need a code that inputs 10 numbers from the user, displays only the distinct numbers and the quantity of distinct numbers ("xxxx distinct #s were entered.")

I am having a hard time displaying the quantity of distinct numbers.

import java.util.Scanner;

class hwFINAL {
    public static void distinctElements(int[] array){
        int count=0;
        int i=0;

        for(i=0;i<array.length;i++){
            boolean isDistinct = false;
            for(int j=0;j<i;j++){
                if(array[i] == array[j]){
                    isDistinct = true;
                    break;
                }
            }
            if(!isDistinct)
                System.out.print(array[i]+",");
        }
    }

    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int arr[] = new int[10];

        for (int i = 0; i < arr.length; i++) {
            System.out.print("Enter numbers " + (i+1) + " : ");
            arr[i] = scan.nextInt();
        }

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

        hwFINAL.distinctElements(arr);
    }
}
rolve
  • 10,083
  • 4
  • 55
  • 75
David c
  • 3
  • 2

3 Answers3

1

Using Java 8

IntStream.of(intArray).distinct().boxed().forEach(System.out::println);

OR

int[] array={1,2,3,4,4,2,2};

String result =IntStream.of(array).distinct().mapToObj(Integer::toString).collect(Collectors.joining(","));
System.out.println(result);

Output: 1,2,3,4

Noor Nawaz
  • 2,175
  • 27
  • 36
0

Try this code. It's simpler IMO.

Scanner scan = new Scanner(System.in);
int arr[] = new int[10];
for (int i = 0; i < arr.length; i++) {
    System.out.print("Enter numbers " + (i+1) + " : ");
    arr[i] = scan.nextInt();
}

Arrays.sort(arr);
int totalUnique = 1;
for (int i = 0; i < arr.length - 1; i++) {
    if (arr[i] != arr[i+1]) {
        totalUnique += 1;
    }
}
System.out.print(totalUnique + " distinct numbers were entered");
Michael
  • 776
  • 4
  • 19
0

Use a HashSet (import java.util.HashSet). By definition, a HashSet cannot store duplicates; therefore your code for the distinctElements() method would be much simpler:

int count;
public static void distinctElements(int[] array){
    HashSet<Integer> set = new HashSet<Integer>();
    for (int i=0; i<array.length; i++){
        set.add(array[i]);
    }
    count = set.size();

    System.out.println(count + " distinct numbers were entered");
}

Then you could also print each distinct number individually using a for-each loop:

for (Integer number : set){
    System.out.println(number);
}
Jonah Haney
  • 521
  • 3
  • 12