103k views
0 votes
Write a method that returns a new array by eliminating the duplicate values in the array using the following method header: Public static int[] eliminateDuplicate(int[] list) Write a test program that reads in 10 integers, invokes the method, and displays the distinct numbers separated by exactly one space. Here is a sample run of the program: Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2 The distinct numbers are: 1 2 3 6 4 5

User MehranTM
by
5.5k points

1 Answer

2 votes

Answer:

Following are the program in java language

import java.util.*; // import package

class Main // main class

{

public static void main(String[] args) // main method

{

Scanner sc = new Scanner(System.in); // creating Scanner class object

int[] num= new int[10]; // declaring the array num

System.out.print("Enter 10 numbers:: ");

for (int i = 0; i < num.length; i++) // iterating over the loop

{

num[i] = sc.nextInt(); // taking 10 input integer.....

}

int[] newList1 = eliminateDuplicates(num);// calling the function eliminateDuplicates

System.out.println("The Distinct numbers are: ");

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

{

System.out.print(" " +newList1[i]); // display the new list

}

System.out.println();

}

public static int[] eliminateDuplicates(int[] list) // method definition as mention in question

{

int[] duplicate1 = new int[10]; // creating the array duplicate

int j = 0, I = 0; // variabe declaration

for (int i = 0; i < list.length; i++) // filling the duplicate with 0

{

duplicate1[i] = 0;

}

int count1 = 0; // variable declaration

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

{

boolean duplicate = false; // creating boolean variable

for(j = 0; j < count1; j++) // iterating over the loop

if(list[i] == duplicate1[j]) // checking the condition

{

duplicate = true; // assigning the duplicate variable to true

break;

}

if(!duplicate) //checking boolean variable duplicate

{

duplicate1[count1] = list[i];

count1++;

}

}

int [] newArray1 = new int[count1]; // creating a new array

for(int i = 0; i < count1; i++) // iterating over the loop

newArray1[i] = duplicate1[i]; // assign the element in the new array

return newArray1; // return array

}

}

Output:

Enter 10 numbers:::1

2

3

2

1

6

3

4

5

2

The Distinct numbers are:1 2 3 6 4 5

Step-by-step explanation:

In this program we create a eliminateDuplicate method and passing array to them.In this function we create a duplicate array and assign 0 to them by iterating over the loop then we check the required condition is duplicate or not by making comparison between the duplicate array and list array i.e if(list[i] == duplicate1[j]) . if matches found then it set duplicate = true; .Finally it created a new array and store the distinct element also return the new array element. In the main method it printed the distinct elements .

User Leth
by
6.1k points