Remove Duplicate Elements from an Integer Array in Java
Write a program in Java to remove all the duplicate elements in a one-dimensional array. The details of the class, its variables and member functions are given below:
Class name: Remove
Data members/instance variables:
a[]: integer array to store the elements
n: to store the size of the array
Methods:
Remove(int m): parameterized constructor to store n = m
void input(): to enter the elements in the array
void duplicate(): to remove all the duplicate elements from the array
void display(): to display the final array
Also write the main() method to create an object of the class and call the methods accordingly to enable the task.
import java.util.Scanner;
class Remove{
int a[];
int n;
public Remove(int m){
n = m;
a = new int[n];
}
public void input(){
Scanner in = new Scanner(System.in);
System.out.println("Enter " + n + " elements:");
for(int i = 0; i < a.length; i++)
a[i] = Integer.parseInt(in.nextLine());
}
public void duplicate(){
for(int i = 0; i < a.length - 1; i++){
for(int j = i + 1; j < a.length; j++){
if(a[i] == a[j])
a[j] = 0;
}
}
}
public void display(){
for(int i = 0; i < a.length; i++){
if(a[i] != 0)
System.out.print(a[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many elements? ");
int size = Integer.parseInt(in.nextLine());
Remove obj = new Remove(size);
obj.input();
obj.duplicate();
obj.display();
}
}
class Remove{
int a[];
int n;
public Remove(int m){
n = m;
a = new int[n];
}
public void input(){
Scanner in = new Scanner(System.in);
System.out.println("Enter " + n + " elements:");
for(int i = 0; i < a.length; i++)
a[i] = Integer.parseInt(in.nextLine());
}
public void duplicate(){
for(int i = 0; i < a.length - 1; i++){
for(int j = i + 1; j < a.length; j++){
if(a[i] == a[j])
a[j] = 0;
}
}
}
public void display(){
for(int i = 0; i < a.length; i++){
if(a[i] != 0)
System.out.print(a[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many elements? ");
int size = Integer.parseInt(in.nextLine());
Remove obj = new Remove(size);
obj.input();
obj.duplicate();
obj.display();
}
}
Comments
Post a Comment