I have to write a program which allows the user to enter 10 integers and displays an error message each time the user enters an integer which was previously input using a HashSet. So far, I have come up with this but the problem is that the error message appears each time I input a number.
package lesson1;
import java.util.*;
public class MyClass1{
public static void main(String[] args) {
Set<Integer> h= new HashSet<Integer>();
Scanner input= new Scanner(System.in);
for(int i=0; i<10;i++){
Object s=h.add(input.nextInt());
if(s!=null){
System.out.println("Duplicates are not allowed");
}
}
System.out.println(h);
}
}
Set.add
returns true if the element exists, otherwise false. You are checking the result for null. You need to change your code to: