In Java, Find Distinct Numbers From Array Of Integers Given By User

import java.util.Scanner;
public class DistinctNumbers{
    public static void main(String[]args){
        int num, cnt = 0, i, j = 0;
        int[]nums=new int[10];
        Scanner in = new Scanner(System.in);
        System.out.print("Enter ten numbers: ");
        while(cnt < nums.length && in.hasNextInt()){
            num = in.nextInt();
            cnt ++;
            i = j;
            while(0 < i-- && nums[i] != num);
            if(-1 == i) nums[j++] = num;
        }
        if(0 == j){
            System.out.println("Error: No inputs given!");
            return;
        }
        System.out.println("The number of distinct numbers is "+j);
        System.out.print("The distinct numbers are:");
        i = 0;  while(i < j) System.out.print(" "+nums[i++]);
    }
}

Comments

Popular posts from this blog