Java Program to find duplicate elements in Array from User Input
DuplicateElement.java
/* Code From Learnoset - Learn Code Online Android App.*/
/*Download Learnoset App from PlayStore to learn coding*/
/*Java Program to find duplicate elements in Array from User Input*/
import java.util.Scanner;
public class DuplicateElement {
public static void main(String[] args) {
//Declare int type array to store user entered values;
int [] numbers;
Scanner scanner = new Scanner(System.in); // Create an object of Scanner Class
System.out.println("Enter size of array");
int sizeOfArray = scanner.nextInt(); // get how many elements user want to store in numbers array;
numbers = new int[sizeOfArray]; // set size of array to store elements from user input
System.out.println("Put elements in array");
for(int i=0; i<sizeOfArray; i++){
// read array element until it reaches the size of array
int arrayElement = scanner.nextInt();
numbers[i] = arrayElement;
}
// Print all elements of numbers array
System.out.println("all elements of array:");
for(int i=0; i<numbers.length; i++){
System.out.print(numbers[i]+", ");
}
System.out.println("\nDuplicate elements in given array: ");
//Searches for duplicate element
for(int i = 0; i < numbers.length; i++) {
for(int j = i + 1; j < numbers.length; j++) {
if(numbers[i] == numbers[j])
System.out.println(numbers[j]);
}
}
/* How above code works?
it will take one by one element of an array then compare one by one with all other elements in array
Ex. if array elements are 1, 2, 3, 1
then first it will take 1 from array and compare it with all other elements
after that it will take 2 and compare it with all other elements... so on*/
}
}
/*----------OUTPUT----------
Enter size of array
5
Enter elements in an array
5
6
2
3
6
all elements of array:
5, 6, 2, 3, 6,
Duplicate elements in given array:
6
*/
Projects with Source Code + Video Tutorials
You can download our Java and Android Studio Projects with Source Code and Video Tutorials.
Programming Quiz App for Android (Offline Version)
Complete Quotes App for Android
Modern Splash Screen with Animations - 01
If you have any Questions or Queries
You can mail us at info.learnoset@gmail.com
Follow us to learn Coding and get in touch with new Technologies.