At Westonci.ca, we provide clear, reliable answers to all your questions. Join our vibrant community and get the solutions you need. Explore thousands of questions and answers from a knowledgeable community of experts on our user-friendly platform. Get quick and reliable solutions to your questions from a community of experienced experts on our platform.

Java programming
*11.13 (Remove duplicates) Write a method that removes the duplicate elements from
an array list of integers using the following header:
public static void removeDuplicate(ArrayList list)
Write a test program that prompts the user to enter 10 integers to a list and displays
the distinct integers separated by exactly one space. Here is a sample run:
Enter ten integers: 34 5 3 5 6 4 33 2 2 4
The distinct integers are 34 5 3 6 4 33 2

Sagot :

Answer:

The program in Java is as follows:

import java.util.*;

public class Main {

public static void removeDuplicate(ArrayList<Integer> list){

 ArrayList<Integer> newList = new ArrayList<Integer>();

 for (int num : list) {

  if (!newList.contains(num)) {

   newList.add(num);  }  }

 for (int num : newList) {

     System.out.print(num+" ");  } }

public static void main(String args[]){

 Scanner input = new Scanner(System.in);

 ArrayList<Integer> list = new ArrayList<Integer>();

 System.out.print("Enter ten integers: ");

 for(int i = 0; i<10;i++){

     list.add(input.nextInt());  }

 System.out.print("The distinct integers are: ");

 removeDuplicate(list);

}}

Explanation:

This defines the removeDuplicate function

public static void removeDuplicate(ArrayList<Integer> list){

This creates a new array list

 ArrayList<Integer> newList = new ArrayList<Integer>();

This iterates through the original list

 for (int num : list) {

This checks if the new list contains an item of the original list

  if (!newList.contains(num)) {

If no, the item is added to the new list

   newList.add(num);  }  }

This iterates through the new list

 for (int num : newList) {

This prints every element of the new list (At this point, the duplicates have been removed)

     System.out.print(num+" ");  } }

The main (i.e. test case begins here)

public static void main(String args[]){

 Scanner input = new Scanner(System.in);

This declares the array list

 ArrayList<Integer> list = new ArrayList<Integer>();

This prompts the user for ten integers

 System.out.print("Enter ten integers: ");

The following loop gets input for the array list

 for(int i = 0; i<10;i++){

     list.add(input.nextInt());  }

This prints the output header

 System.out.print("The distinct integers are: ");

This calls the function to remove the duplicates

 removeDuplicate(list);

}}