We have introduced ArrayList in the lecture. As you know, ArrayList object can b
ID: 3793828 • Letter: W
Question
We have introduced ArrayList in the lecture. As you know, ArrayList object can be used to store a list of objects. In this problem, we would like you to practice using it to process data. Assume the user can input a list of numbers. Please write a method that removes the duplicate elements from an array list of integers using the following header: public static void removeIdenticalNumbers(ArrayList 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. Expected results: 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 32Explanation / Answer
package sample;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class lib {
public static void main(String args[]) {
ArrayList<Integer> al=new ArrayList<Integer>();
System.out.println("enter integers(ends with character q) : ");
Scanner s=new Scanner(System.in);
char ch;
ch='0';
while(ch!='q'){
ch=s.next().charAt(0);
if(Character.isDigit(ch))
{
al.add(new Integer(Character.getNumericValue(ch)));
}
}
removeIdenticalNumbers(al);
}
public static void removeIdenticalNumbers(ArrayList<Integer> al){
ArrayList<Integer> al1=al;
for(int i=0;i<al.size();i++){
int count=0;
for(int j=0;j<al1.size();j++){
if(al.get(i).intValue()==al1.get(j).intValue())
{
if(count>0)al1.remove(j);
count++;
}
}
}
for(int i=0;i<al1.size();i++){
System.out.print(al1.get(i).intValue()+" ");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.