Answer:
The program to this question can be given as:
Program:
//import package.
import java.util.*;
public class Main //defining the class
{
public static void main(String[] args) //defining main method
{
Scanner ob = new Scanner(System.in); //creating scanner class object.
int[] a = new int[10];//define array.
int number,counts= 0,i;//define variable.
System.out.print("Enter numbers: "); //message.
for (i = 0; i < 10; i++) //loop
{
number=ob.nextInt();
if (isDistinct(a,number))
{
a[counts] = number;//assign value in array
counts++; // Increment count
}
}
System.out.println("The distinct numbers is :" + counts);
System.out.print("The distinct number are :");
for (i = 0; i <a.length; i++)//loop
{
if (a[i] > 0)
{
System.out.print(" " +a[i]);//print array.
}
}
System.out.println();
}
public static boolean isDistinct(int[] array, int num)//defining method
{
for (int i = 0; i < array.length; i++)//loop for check number
{
if (num == array[i]) //check condition
{
return false; //return value false.
}
}
return true; //return value true
}
}
Output:
First time run:
Enter ten numbers: 1 2 3 4 5 6 7 8 9 10
The number of distinct numbers is 10
The distinct numbers are 1 2 3 4 5 6 7 8 9 10
Second time run:
Enter numbers: 2 3 5 8 7 4 3 2 1 2
The distinct numbers is :7
The distinct number are : 2 3 5 8 7 4 1
Explanation:
The description of the above java code can be given as:
- In the above java code, a class is defined that is main inside a class-main function is defined in the main function firstly creating a scanner class object that is "ob" then define variables and array that are number, counts and a[].
- To inserts array elements we use a loop. In the loop, we use integer variable number and define a condition in if block passes a function that check value count total value.
- In the second loop, we check the condition that array elements value is greater than 0 and print all array elements.
- The isDistinct function checks in the array two values are not the same. if the values are the same it will return false value because this function is the boolean type that returns an only boolean value.