In: Computer Science
in java
Write a program that reads in ten numbers and displays the number of distinct numbers and the distinct numbers separated by exactly one space (i.e., if a number appears multiple times, it is displayed only once). (Hint: Read a number and store it to an array if it is new. If the number is already in the array, ignore it.) After the input, the array contains the distinct numbers. Here is the sample run of the program:
Enter the numbers: 1 2 3 4 5 6 1
Number of distinct numbers: 6
Numbers: 1 2 3 4 5 6
import java.util.Scanner; public class DistinctArray { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter the numbers: "); int[] numbers = new int[10]; int n, size = 0; boolean found; for (int i = 0; i < 10; i++) { n = in.nextInt(); found = false; for (int j = 0; j < size; j++) { if (numbers[j] == n) { found = true; } } if (!found) { numbers[size++] = n; } } System.out.println("Number of distinct numbers: " + size); System.out.print("Numbers:"); for (int i = 0; i < size; i++) { System.out.print(" " + numbers[i]); } System.out.println(); } }