I was provided a list of students' ID numbers to use during the enrolment process. She discovered, however, that some ID numbers are duplicated in some cases. To avoid duplication, she intended to first encode all of the ID numbers. You must assist me in resolving my difficulty by developing a program that allows me to enter the Id numbers without fear of duplication. my program should be able to display the list of ID numbers at the end
import java.util.Scanner;
public class ID_NUm {
public static void main(String[] args) {
int size;
Scanner sc = new Scanner(System.in);
System.out.print("How many students? ");
size = sc.nextInt();
int InpNum[] = new int[size];
System.out.print("\n");
for (int i = 0; i < size; i ) {
System.out.print("Enter ID number: ");
InpNum[i] = sc.nextInt();//this is the part where you should identify if the number is duplicated or not, and I don't know how to code that
}
System.out.print("\nList of ID number entered:\n\n");
for (int i = 0; i < size; i ) {
System.out.print("Enter ID number:" InpNum[i] " \n");
}
}
}
CodePudding user response:
You're looking to use a HashSet
, which is built-in to Java. This is a datastructure which you can insert elements into, and also check if a certain element exists in constant time. Thus, when you read in an element, first check if the set contains said element; if so, skip it, otherwise, put it in your list of IDs and also insert it into your HashSet. You can see the documentation here