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

--JAVA Program-- ArrayList objects can be used to store a list of objects. Assum

ID: 3670918 • Letter: #

Question

--JAVA Program--

ArrayList objects can be used to store a list of objects. Assume the user can input a list of numbers, write a method that removes the duplicate elements from an array list of integers using the following signature: public static void removeIdenticalNumbers(ArrayList<Integer> list)

Write a test program that prompts the user to enter unlimited number of integers to a list (end with a character ‘q’ to finish the input) and displays the distinct integers separated by exactly one space.

Sample Test Case: Enter integers (end with character 'q'): 2 3 3 12 21 21 23 5 6 6 43 77 32 12 q The distinct integers: 2 3 12 21 23 5 6 43 77 32

Explanation / Answer

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;

/**
* @author srinu
*
*/
public class RemoveIdentical {
   /**
   * @param args
   */
   public static void main(String[] args) {

       Scanner scanner = null;
       ArrayList<Integer> list = new ArrayList<Integer>();
       try {
           scanner = new Scanner(System.in);
           System.out.print("Enter integers (end with character 'q'):");
           // reading ints until enters q
           do {
               String inVal = scanner.next();
               if (inVal.equals("q"))
                   break;
               else
                   // adding to list
                   list.add(Integer.parseInt(inVal));
           } while (true);

           System.out.print("The distinct integers:");
           // creating iterator after removing duplicates
           Iterator<Integer> listIT = removeIdenticalNumbers(list).iterator();
           while (listIT.hasNext()) {
               // printing identical ints
               System.out.print(listIT.next() + " ");

           }

       } catch (Exception e) {
           // TODO: handle exception
       }

   }

   /**
   * method that removes the duplicate elements from an arraylist list
   *
   * @param list
   * @return
   */
   public static ArrayList<Integer> removeIdenticalNumbers(
           ArrayList<Integer> list) {

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

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

           int num = list.get(i);

           if (!usedList.contains(num)) {
               usedList.add(num);
               newList.add(num);
           }
       }

       return newList;
   }

}

OUTPUT:

Enter integers (end with character 'q'):2 3 3 12 21 21 23 5 6 6 43 77 32 12 q
The distinct integers:2 3 12 21 23 5 6 43 77 32