Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Book exercise 6.5: (Printing distinct numbers) Write a program that reads in ten

ID: 3620600 • Letter: B

Question

Book exercise 6.5: (Printing distinct numbers)
Write a program that reads in ten numbers and displays distinct numbers (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 new. If the number is already in the array, ignore it. After the input, the array contains the distinct numbers. Here is a sample run of the program (sample input is underlined for emphasis only):

Enter ten numbers:
1 2 3 2 1 6 3 4 5 2
The distinct numbers are: 1 2 3 6 4 5

Explanation / Answer

import java.util.Scanner;

/**
*
* @author ashok
*/
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner sin = new Scanner(System.in);
        int [] distinctArray = new int[10];
        int temp = 0;
        int index = 0;
        outer:for(int i=0;i<10;i++)
        {
            System.out.println("Please enter number" + (i+1));
            temp = sin.nextInt();
            for(int j=0;j<=i;j++)
                if(temp==distinctArray[j])
                    continue outer;
            distinctArray[index++] = temp;
        }
        for(int i=0;i<index;i++)
            System.out.println(distinctArray[i]);
    }

}