96.2k views
3 votes
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

1 Answer

4 votes

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);

}}

Step-by-step 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);

}}

User Morne
by
3.6k points