In: Computer Science
IN java
Create a New Java Project called LastNameDuplicate.
//Given an array of N elements with each element between 1 and N, write a program to determine whether there are any duplicates.
//You must prompt the user for the array elements.
//Display the contents of the array, along with the values that are duplicated and how many times they appeared in the array.
//NOTE: N should be at least 15. Input Validation: Verify that each element entered has a value between 1 and N. If an incorrect value is entered, continuously prompt for a new value. This should not halt or terminate your program.
Java Program:
/* Java Program that reads elements in to array and displays duplicate count */
import java.util.*;
class Duplicates
{
public static void main(String args[])
{
Scanner sc = new
Scanner(System.in);
int i, j;
//Reading number of elements
System.out.print("\n Specify number
of elements: ");
int N = sc.nextInt();
//Array to hold input
elements
int[] arrayElements = new
int[N];
//Reading integers from the
console
System.out.println("\n Enter array
elements: ");
for (i = 0; i < N; i++)
{
//Loop till user
enters a valid value
do
{
//Reading value
arrayElements[i] = sc.nextInt();
}while(arrayElements[i] < 1 || arrayElements[i] > N);
}
//Printing array elements
System.out.println("\n\n Array
Elements: \n");
for(i=0; i<N; i++)
{
System.out.print(" \t " + arrayElements[i]);
}
int temp;
//Sorting array
for(i=0; i<N; i++)
{
for(j=i+1;
j<N; j++)
{
//Comparison
if(arrayElements[i] > arrayElements[j])
{
//Swapping
temp =
arrayElements[i];
arrayElements[i] =
arrayElements[j];
arrayElements[j] =
temp;
}
}
}
boolean duplicate;
int count;
System.out.println("\n\n");
//Searching for duplicate elements
and storing count
for (i = 0; i < N;)
{
duplicate =
false;
count = 1;
//Searching over
next position elements
for (j = i+1; j
< N; j++)
{
//If there is no match then break loop
if(arrayElements[j] != arrayElements[i])
break;
//Comparing elements
if (arrayElements[i] == arrayElements[j]
&& j!=i)
{
//Incrementing count
count ++;
duplicate = true;
}
}
//Printing
duplicate element
if(duplicate)
{
i = i+count-1;
System.out.println("\n Element: " +
arrayElements[i] + " \t " + count + " times \n");
}
else
i = i+1;
}
}
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
Sample Output: