Given an array of N elements with each element between 1 and N, write a Java pro
ID: 3793844 • Letter: G
Question
Given an array of N elements with each element between 1 and N, write a Java 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. Please show comments.
Explanation / Answer
DuplicateValuesCheck.java
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
public class DuplicateValuesCheck {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the array size: ");
int n = scan.nextInt();
int a[] = new int[n];
for(int i=0; i<a.length; i++){
System.out.println("Enter the value: ");
a[i] = scan.nextInt();
if(a[i] <1 || a[i]> n){
System.out.println("Invalid number. Number must be between 1 and "+n);
i--;
}
}
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0; i<a.length; i++){
if(map.containsKey(a[i])){
map.put(a[i], map.get(a[i])+1);
}
else{
map.put(a[i], 1);
}
}
System.out.println("Array elements: "+Arrays.toString(a));
Iterator itr = map.keySet().iterator();
while(itr.hasNext()) {
Integer key = (Integer)itr.next();
Integer value = map.get(key);
System.out.println("Number: "+key+" Times: "+value);
}
}
}
Output:
Enter the array size:
15
Enter the value:
1
Enter the value:
2
Enter the value:
3
Enter the value:
4
Enter the value:
5
Enter the value:
6
Enter the value:
5
Enter the value:
4
Enter the value:
5
Enter the value:
6
Enter the value:
1
Enter the value:
1
Enter the value:
1
Enter the value:
1
Enter the value:
4
Array elements: [1, 2, 3, 4, 5, 6, 5, 4, 5, 6, 1, 1, 1, 1, 4]
Number: 1 Times: 5
Number: 2 Times: 1
Number: 3 Times: 1
Number: 4 Times: 3
Number: 5 Times: 3
Number: 6 Times: 2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.